Java 枚举 getDeclaringClass 与 getClass [英] Java Enum getDeclaringClass vs getClass

查看:20
本文介绍了Java 枚举 getDeclaringClass 与 getClass的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java Enum 类的文档说明了以下关于 getDeclaringClass 的内容:

The docs for the Java Enum class state the following about getDeclaringClass:

返回对应的Class对象到这个枚举常量的枚举类型.二枚举常量 e1 和 e2 是相同的枚举类型当且仅当e1.getDeclaringClass() ==e2.getDeclaringClass().(价值此方法返回的可能不同从返回的那个枚举的 Object.getClass() 方法具有常量特定类的常量身体.)

Returns the Class object corresponding to this enum constant's enum type. Two enum constants e1 and e2 are of the same enum type if and only if e1.getDeclaringClass() == e2.getDeclaringClass(). (The value returned by this method may differ from the one returned by the Object.getClass() method for enum constants with constant-specific class bodies.)

我不明白 getClassgetDeclaringClass 何时不同.有人可以提供一个例子和解释吗?

I don't understand when getClass and getDeclaringClass are different. Can someone provide an example along with an explanation?

推荐答案

Java 枚举值允许具有特定于值的类主体,例如(我希望这个语法是正确的...)

Java enum values are permitted to have value-specific class bodies, e.g. (and I hope this syntax is correct...)

public enum MyEnum {

   A {
       void doSomething() { ... }
   },


   B {
       void doSomethingElse() { ... }
   };
}

这将生成表示AB 的类主体的内部类.这些内部类将是 MyEnum 的子类.

This will generate inner classes representing the class bodies for A and B. These inner classes will be subclasses of MyEnum.

MyEnum.A.getClass() 将返回代表 A 类主体的匿名类,这可能不是你想要的.

MyEnum.A.getClass() will return the anonymous class representing A's class body, which may not be what you want.

MyEnum.A.getDeclaringClass() 另一方面,将返回表示 MyEnumClass 对象.

MyEnum.A.getDeclaringClass(), on the other hand, will return the Class object representing MyEnum.

对于简单的枚举(即没有特定于常量的类主体的枚举),getClass()getDeclaringClass() 返回相同的内容.

For simple enums (i.e. ones without constant-specific class bodies), getClass() and getDeclaringClass() return the same thing.

这篇关于Java 枚举 getDeclaringClass 与 getClass的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆