枚举:独占于每个实例的方法 [英] Enums: methods exclusive to each one of the instances

查看:129
本文介绍了枚举:独占于每个实例的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另一个问题,我了解到可以在Java中为每一个定义具体的方法枚举的实例:

From another question I have learnt that it is possible in Java to define specific methods for each one of the instances of an Enum:

public class AClass {

    private enum MyEnum{
        A { public String method1(){ return null; } },
        B { public Object method2(String s){ return null; } },
        C { public void method3(){ return null; } } ;
    }

    ...
}

我很惊讶,这甚至是可能的,这样每个实例具体的独家方法都有一个名称来寻找文档?

I was surprised that this is even possible, do this "exclusive methods" specific to each instance have a name to look for documentation?

另外,应该如何使用?因为下一个没有编译:

Also, how is it supposed to be used? Because the next is not compiling:

    private void myMethod () {
        MyEnum.A.method1();
    }

我应该如何使用这些独家方法?

How am I supposed to use these "exclusive" methods?

推荐答案

您不能引用这些方法,因为您正在为每个枚举有效地创建匿名(*)类。由于它是匿名的,您只能从匿名类本身或通过反射来引用这些方法。

You cannot refer to those methods, because you are effectively creating anonymous (*) class for each enum. As it is anonymous, you can reference such methods only from inside your anonymous class itself or through reflection.

当您在枚举中声明抽象方法时,此技术非常有用,并且为每个枚举单独实现该方法。

This technique is mostly useful when you declare abstract method in your enumeration, and implement that method for each enum individually.

(*)JLS 8.9枚举部分说:枚举常量的可选类体隐式定义一个匿名类声明(§ 15.9.5)扩展了紧邻的枚举类型。

(*) JLS 8.9 Enums part says: "The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type."

这篇关于枚举:独占于每个实例的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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