简体   繁体   English

Java枚举类型名称反映

[英]Java enum type name reflection

I want to retrieve the name of the enum type from within the enum type itself: 我想从枚举类型本身中检索枚举类型的名称:

enum Mammals {
    DOG(new Dog()),
    CAT(new Cat());

    public String alias;

    Mammals(AncestorOfDogAndCat a){
        this.alias=this.getClass().getName().toLowerCase();
        System.out.println(alias);
    }
}

When I instance them I get 当我实例化它们时,我得到

Main$mammals
Main$mammals

but I want 但我想要

dog
cat

Don't use reflection. 不要使用反射。 It's not robust enough. 它不够健壮。 Provide a method which provides this information. 提供一种提供此信息的方法。

interface Animal
{
    String getName();
}

class Dog implements Animal
{
    public String getName()
    {
        return "dog";
    }
}

enum Mammals {
    DOG(new Dog()),
    CAT(new Cat());

    public String alias;

    Mammals (Animal animal) {
        this.alias = animal.getName();
        System.out.println(alias);
    }
}

You can use the name() method on an enum constant to get the name of the enum constant: 您可以在枚举常量上使用name()方法来获取枚举常量的名称:

enum Mammals {
    DOG(),
    CAT();

    public String alias;

    Mammals() {
        this.alias = name().toLowerCase();
        System.out.println(alias);
    }
}

The name() method is something that is automatically added by the compiler on enum types. name()方法是编译器在enum类型上自动添加的。

enum Mammals {
    DOG(new Dog()),
    CAT(new Cat());

    public String alias;

    Mammals(DogOrCat value){
        this.alias=name().toLowerCase();
        System.out.println(alias);
    }
}

or use toString() , which by default is implemented using name . 或使用toString() ,默认情况下是使用name实现的。

Using this.getClass() will return the name of the class itself, which is the enum Mammals here. 使用this.getClass()将返回类本身的名称,这里是哺乳动物的枚举。 Instead take in a parameter and use getClass on the parameter for your alias. 取一个参数,并在参数上使用getClass作为别名。

enum Mammals {
DOG(new Dog()),
CAT(new Cat());

public String alias;

  Mammals(Animal an){
      this.alias=an.getClass().getName().toLowerCase();
      System.out.println(alias);
  }
}

where Dog and Cat extend Animal. 狗和猫延伸动物的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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