vendredi 27 septembre 2019

Instantiate object of a given class implementing an interfacte and add it to a List

I have an Interface "Instruction" and some instructions implement it (Add, Sub, Mul, Jmp...), to execute this instructions I store them on a List object and call an execute() method afterwards. I am reading this instructions from a file and I want to instantiate the proper class by means of the String read from the file but when I invoke the constructor.newInstance(...) I lose the type of the reference and I wont be able to invoke the methods without instanceofs and dirty casts (I want to avoid them).

List<Instruction> res = new ArrayList<>()
String className = "Add";
Class<?> classLoaded = Class.forName("instructions." + className);
Constructor<?> constructor = classLoaded.getConstructors()[0];
Object obj = constructor.newInstance(paramsOfConstructor);
res.add(obj);

This works as I want it to work but I want to avoid dirty casts as much as possible

Instruction obj = (Instruction) constructor.newInstance(paramsOfConstructor);
res.add(obj);

PD: paramsOfConstructor are all the objects/primitives I give to the constructor, I don´t include the code to obtain them because that would be a copy/paste of 30 or so lines. If needed I can copy them also.





Aucun commentaire:

Enregistrer un commentaire