java - 如何在 Java 中使用反射创建枚举实例?

标签 java reflection enums

当我在阅读 Effective Java 时,作者告诉我单元素 enum 类型是实现单例的最佳方式,因为我们不必须考虑复杂的序列化或反射攻击。这意味着我们不能使用反射创建 enum 的实例,对吧?

我做了一些测试,这里有一个 enum 类:

public enum Weekday {}

然后我尝试创建一个 Weekday 的实例:

Class<Weekday> weekdayClass = Weekday.class;
Constructor<Weekday> cw = weekdayClass.getConstructor(null);
cw.setAccessible(true);
cw.newInstance(null);

如您所知,这是行不通的。当我将关键字 enum 更改为 class 时,它起作用了。我想知道为什么。谢谢。

最佳答案

这是内置在语言中的。来自Java Language Specification (§8.9) :

It is a compile-time error to attempt to explicitly instantiate an enum type (§15.9.1). The final clone method in Enum ensures that enum constants can never be cloned, and the special treatment by the serialization mechanism ensures that duplicate instances are never created as a result of deserialization. Reflective instantiation of enum types is prohibited. Together, these four things ensure that no instances of an enum type exist beyond those defined by the enum constants.

这样做的全部目的是允许安全地使用 == 来比较 Enum 实例。

编辑:参见 the answer by @GotoFinal了解如何使用反射打破这种“保证”。

关于java - 如何在 Java 中使用反射创建枚举实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9614282/

相关文章:

c# - 通用方法,取消装箱可为 null 的枚举

c++ - 在 C++ 0x 中打开枚举类

java - 使用 2D 图形在 Java 中绘制随机点

java - 确保标题在 JOptionPane 上完全可见

c# - 创建 C# 属性以抑制方法执行

C# - 将 'object' 参数转换为该对象的类型?

java - 如何将jdatechooser中的日期值插入到数据库表中

java - 如何替换文本文件.java中的特定行

c# - 在运行时从以编程方式创建的 UserControl 中检索 XAML

c# - 将 linq 查询结果转换为枚举