[英]Get class instance from enum type
I have the Color
enum with: 我有以下Color
枚举:
RED
BLUE
GREEN
I also have these 3 classes: 我也有以下3个课程:
Red
Blue
Green
My Testclass
uses the attribute private Color color
and stores one enum value there. 我的Testclass
使用属性private Color color
并在其中存储一个枚举值。 How can I return the corresponding class object when calling getValue()
or something on private Color color
? 调用getValue()
或private Color color
上的内容时,如何返回相应的类对象?
Example: If my Testclass
has color = Color.RED
, it should return a new instance of the class Red
when calling getValue()
on it. 示例:如果我的Testclass
color = Color.RED
,则在对它调用getValue()
时应返回类Red
的新实例。
You can make the enum
a factory. 您可以将enum
工厂。
interface AColour {
};
static class Red implements AColour {
}
static class Green implements AColour {
}
static class Blue implements AColour {
}
enum Colour {
RED {
@Override
AColour makeColour() {
return new Red();
}
},
GREEN {
@Override
AColour makeColour() {
return new Green();
}
},
BLUE {
@Override
AColour makeColour() {
return new Blue();
}
};
abstract AColour makeColour();
}
class TestClass {
Colour colour = Colour.RED;
AColour make() {
return colour.makeColour();
}
}
I originally suggested a static map of Color enums to classes but chrylis pointed out in the comments it's simpler just to make it a field and pass it to the constructor. 我最初建议将Color枚举的静态映射映射到类,但chrylis在注释中指出,将其设为字段并将其传递给构造函数更简单。
public enum Color {
RED(Red.class),
BLUE(Blue.class),
GREEN(Green.class);
private Class colorClass;
public Color(Class classColor) {
this.colorClass = classColor;
}
public ColorClass getValue() {
return this.colorClass.newInstance();
}
}
See Class.forName(String)
. 请参见Class.forName(String)
。
Returns the
Class
object associated with the class or interface with the given string name. 返回具有给定字符串名称的与类或接口关联的Class
对象。
Do not forget to put the full package name of the target. 不要忘记输入目标的完整软件包名称。 Then you should declare the Color
enum like this. 然后,您应该像这样声明Color
枚举。
public enum Color {
RED("package.Red"),
BLUE("package.Blue"),
GREEN("package.Green");
private final String value;
private Color(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
You may need a specific instance, not just a Class
instance. 您可能需要一个特定的实例,而不仅仅是一个Class
实例。
try {
Class clazz = Class.forName(Color.RED.getValue());
if (clazz.isInstance(Red.class)) {
Red red = (Red)clazz.cast(Red.class);
} else if (clazz.isInstance(Blue.class)) {
Blue blue = (Blue)clazz.cast(Blue.class);
} else if (clazz.isInstance(Green.class)) {
Green green = (Green)clazz.cast(Green.class);
}
} catch (ClassNotFoundException classNotFound) {
// A class named "package.Red" cannot be found
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.