[英]Java - Get instances of abstract class by <class ? extends SuperClass> with parameters
Excuse me if the Title is rather vague. 如果标题含糊不清,请问。
Allow me to elaborate my problem: 请允许我详细说明我的问题:
Imagine I have a class called "Car", which is an abstract class. 想象一下,我有一个名为“ Car”的类,它是一个抽象类。 Now imagine I have multiple instances of Car, for example Audi, Volvo, Ferrari etc. 现在,假设我有多个Car实例,例如Audi,Volvo,Ferrari等。
I want to store these instances in an enum class, so I can easily retrieve them by the enum. 我想将这些实例存储在枚举类中,这样我就可以轻松地通过枚举检索它们。 The problem, however, is that every instance has an parameter in it's constructor, that I cannot put as a final attribute within the enum. 但是,问题在于,每个实例的构造函数中都有一个参数,因此我不能将其作为枚举的最终属性。 I need to get the instances of the superclass (with 1 parameter) created from .class. 我需要获取从.class创建的超类(带有1个参数)的实例。
Pseudo code 伪代码
/* This is my super class */
public abstract class Car{
public Car(Object param){ }
}
/* This is my instance */
public class Volvo extends Car{
public Volvo(Object param){
super(param);
}
}
/* This is my other instance */
public class Ferrari extends Car{
public Ferrari(Object param){
super(param);
}
}
The code above is a proper display of the classes I made. 上面的代码正确显示了我制作的类。 Allright, now the enum class: 好了,现在是枚举类:
public enum CarType{
VOLVO(Volvo.class), FERRARI(Ferrari.class);
private Class<? extends Car> instance;
private CarType(Class<? extends Car> instance){
this.instance = instance;
}
/* This is what I tried, NOT working*/
public Car getCarInstance(Object param){
try{
return Car.class.getConstructor(instance).newInstance(param);
}catch(Exception e){
/* I didn't do bugmasking, but all the exceptions would
make this post look messy.*/
}
}
}
What I need as result: If I would've called 'CarType.VOLVO.getCarInstance("My parameter value"); 结果需要什么:如果我将调用'CarType.VOLVO.getCarInstance(“ My parameter value”); ' it would be the same as 'new Volvo("my parameter value");' '它将与'new Volvo(“ my parameter value”);'相同。
Thanks in advance. 提前致谢。
在getCarInstance更改行后,尝试执行以下操作:
return instance.getConstructor(Object.class).newInstance(param);
You don't need Car.class
because you already specified the type in your enum constructor. 您不需要Car.class
因为您已经在枚举构造函数中指定了类型。 By the way, don't call it instance , call it type . 顺便说一句,不要叫它实例 ,叫它type 。
Here we go: 开始了:
public Car getCarInstance(Object param) {
try {
return type.getConstructor(Object.class).newInstance(param);
} catch (ReflectiveOperationException e) {
throw new IllegalStateException(e);
}
}
The second thing (as you can see) is, how to retrieve the correct constructor. 第二件事(如您所见)是如何检索正确的构造函数。 Read more about reflection if you want to know more. 如果您想了解更多信息,请阅读更多有关反射的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.