Raghu Vijaykumar
Raghu Vijaykumar

Reputation: 341

Get specific class based on enum on compile

I am trying to get class resolved to specific type based on enum type.

public enum PipelineType {

     A(X.class, XConfig.class),
     B(Y.class, YConfig.class);

     public final Class<?> pipelineClazz; 
     public final Class<?> pipelineConfigClazz;

     PipelineType(Class<?> pipelineClass,
               Class<?> pipelineConfigClazz) {
          this.pipelineClazz = pipelineClass;
          this.pipelineConfigClazz = pipelineConfigClazz;
     }
     
     public Object getPipelineClassObject() {
          try {
               return this.pipelineClazz.newInstance(); // is there a way to get the specifc class object based on Enum PipelineType.A get X and XConfig object.  
          } catch (InstantiationException | IllegalAccessException e) {
               e.printStackTrace();
          }
          return null;
     }
}

Am i doing something wrong here?

Upvotes: 0

Views: 101

Answers (1)

daniu
daniu

Reputation: 14999

Add a Supplier<?> to the constructor.

enum PipelineType {
 X(() -> new XType()),
 Y(() -> new YType());
 Supplier<?> create;
 private PipelineType(Supplier<?> creator) {
  create = creator;
 }
 public <T> T createPipelineObject() {
  return (T)create.get();
 }
}

Upvotes: 2

Related Questions