gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 20:55:57 24 4
gpt4 key购买 nike

当我在阅读 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com