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

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

问题描述

当我阅读有效的java时,作者告诉我,单元素枚举类型是实现单例的最好方式,因为我们不必考虑复杂的
序列化或反射攻击。这意味着我们无法使用反射创建枚举的实例,这是对的吗?
我已经做了一些测试,这里有一个枚举类:

When I'm reading the "effective java", 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, is this right? I have done some test, an enum class here:

    public enum 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 pre.

推荐答案

这是内置的语言。从 Java语言规范(§8.9)

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


尝试显式实例化枚举类型(§15.9.1)是一个编译时错误。 Enum中的最终克隆方法可确保枚举常量永远不会被克隆,并且序列化机制的特殊处理可确保重复的实例不会因反序列化而被创建。枚举类型的反射实例被禁止。总而言之,这四个事情确保不存在枚举类型定义的枚举类型的实例。

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.

是允许安全使用 == 来比较枚举实例。

The whole purpose of this is to allow the safe use of == to compare Enum instances.

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

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