[英]Java casting enum to a class
I have a class which is identical to enum. 我有一个与枚举相同的类。 The only difference is that I create the class so that I can dynamically create the enums.
唯一的区别是,我创建了类,以便可以动态创建枚举。 What I want is to override the cast operation of enum so that I can give the enum instance to a method where it gets the class instance.
我要覆盖的是enum的强制转换操作,以便我可以将enum实例提供给获取类实例的方法。
Example: 例:
public enum SpecialEnum {
FIRST("First"), SECOND("Second");
private String name;
SpecialEnum(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class SpecialClass {
private String name;
public SpecialClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public void displayName(SpecialClass specialClass) {
System.out.println(specialClass.getName());
}
Lets say that the SpecialClass instances are coming from a server where I display them. 可以说SpecialClass实例来自我在其中显示它们的服务器。 But I also want to use my pre-defined Special enum classes as well.
但是我也想使用我预定义的Special枚举类。 I know that I could create static instances of SpecialClass and use them but not that it looks messy, also using enums are beneficial to my occasion as well.
我知道我可以创建SpecialClass的静态实例并使用它们,但是看起来不很乱,而且使用枚举对我的场合也有好处。 Is there a way to override casting operation of the enum class of a work around maybe?
有没有办法可能覆盖工作枚举类的强制转换操作?
Extract an interface
: 提取
interface
:
public interface Named {
public String getName();
}
public class SpecialClass implements Named {
private String name;
public SpecialClass(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
}
public enum SpecialEnum implements Named {
FIRST("First"), SECOND("Second");
private String name;
SpecialEnum(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
}
public void displayName(Named specialClass) {
System.out.println(specialClass.getName());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.