简体   繁体   中英

How can I get the enum class from a variable?

Best explained in code.

I have something like this

public enum MyEnum implements MyEnumInterface { 
   A,
   B,
   C
}

public enum MyOtherEnum implements MyEnumInterface { 
   AA,
   BB,
   CC
}

and somewhere else

public void doSomething(MyEnumInterface anEnum, ... ) {
   ... 
   // doSomething 
   ... 
}

I would like to find out what class anEnum comes from (eg MyEnum or MyOtherEnum).

How can I do that? (without doing an instanceof check for all possible implementations :) )

You need to call .getDeclaringClass() on the enum value to get the class. But I think you are in search of the Visitor Pattern :

public class Example implements Visitor {

    public static void main(String[] args) {
        Example example = new Example();
        example.doSomething(MyEnum.A);
        example.doSomething(MyOtherEnum.BB);
    }

    public void doSomething(MyEnumInterface anEnum) {
        anEnum.visit(this);
    }

    @Override public void visit(MyEnum my) {
        System.out.println("MyEnum: " + my);
    }

    @Override public void visit(MyOtherEnum my) {
        System.out.println("MyOtherEnum: " + my);
    }
}

interface Visitor {

    public void visit(MyEnum my);

    public void visit(MyOtherEnum my);
}

interface MyEnumInterface {
    public void visit(Visitor visitor);
}

enum MyEnum implements MyEnumInterface { 
    A,
    B,
    C;

    @Override public void visit(Visitor visitor) {
        visitor.visit(this);
    }
 }

 enum MyOtherEnum implements MyEnumInterface { 
    AA,
    BB,
    CC;

    @Override public void visit(Visitor visitor) {
        visitor.visit(this);
    }
}    

This is the answer to your comment:

public static void main(String[] args) {
    System.out.println(MyEnum.A.getDeclaringClass());
}

OUTPUT:

class MyEnum

You can do it by accessing its class object:

System.out.println(anEnum.getDeclaringClass().getName());

Note that getDeclaringClass() is critically different from getClass() when each value has a custom class body. More information

Enums are also classes so use

if(anEnum instanceof MyEnum) {...}

and

if(anEnum instanceof MyOtherEnum) {...}

您可以使用instanceof运算符来确定对象的类型

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM