简体   繁体   中英

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. Now imagine I have multiple instances of Car, for example Audi, Volvo, Ferrari etc.

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.

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"); ' it would be the same as '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. By the way, don't call it instance , call it 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.

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