jeudi 11 juin 2015

Creating a new object based on enum type and reflection [duplicate]

This question already has an answer here:

For academic purposes I'm coding a small set of classes. My aim is to create a new object based on enum types using a method on a static factory class that uses reflection to build the object it self.

My aproach:

Created enum class with several enum types a constructor with string parameter and toString method.

public enum Type {

  A("ClassA"),
  B("ClassB"),
  C("ClassC"),
  D("ClassD"),
  E("ClassE");

  private final String _text;

  Type(String someText){
      this._text = someText;
  }

  @Override
  public String toString() {
    return this._text;
  }
}

Now, my factory class takes advantage of enum type and uses reflection to create the object instance.

public class Factory {

    public static MyType createType(Type type) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
        return (MyType) Class.forName(type.toString()).newInstance();
    }

}

This is how I call it in my main method...

//superclass of ClassA, ClassB, ClassB...
MyType ct = null;

try {
   ct = Factory.createType(type);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e ){
   System.err.println("Some error ocured "+e.getMessage()+" - ");
}

EDIT: This code will not build a new instance, most probably error will be in enum class, the stack trace is pointing to this line: (MyType) Class.forName(type.toString()).newInstance(); with Class not found

I believe that some simple solution will solve this... Any way this opens a discussion on which is best practices to build new instance object based on enum types. Hoping your collaboration, thank you all.





Aucun commentaire:

Enregistrer un commentaire