如何在 Java 中使用反射创建枚举实例? [英] How to create an instance of enum using reflection in Java?

查看:50
本文介绍了如何在 Java 中使用反射创建枚举实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I'm reading Effective Java, the author told me that a single-element enum type is the best way to implement a singleton, because we don't have to consider sophisticated serialization or reflection attacks. This means we cannot create an instance of enum using reflection, right?

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

I have done some tests, with an enum class here:

public enum Weekday {}

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

Then I tried to create an instance of Weekday:

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

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

As you know, it doesn't work. When I change the key word enum to class, it works. I want to know why. Thank you.

推荐答案

这是语言内置的.来自 Java 语言规范 (§8.9):

This is built into the language. From the Java Language Specification (§8.9):

尝试显式实例化枚举类型是编译时错误(第 15.9.1 节).Enum 中的最终 clone 方法确保永远无法克隆枚举常量,并且序列化机制的特殊处理确保永远不会因反序列化而创建重复实例.禁止枚举类型的反射实例化.这四件事一起确保了枚举类型的实例不存在于枚举常量定义的实例之外.

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 whole purpose of this is to allow the safe use of == to compare Enum instances.

请参阅@GotoFinal 的答案,了解如何使用反射打破这个保证".

See the answer by @GotoFinal for how to break this "guarantee" using reflection.

这篇关于如何在 Java 中使用反射创建枚举实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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