mardi 10 juillet 2018

Loading class based on its name

Is there a way how to load a class based on its name?

For example, lets say i want to dynamicly create instance of class, where i have the name of the class as input. I have tried the following:

Class loadedClass = Class.forName("com.project.Cars.SportCar");
    Constructor<Object> t = loadedClass.getConstructor(String.class,int.class,int.class);
    Car tt = (Car) t.newInstance("hi",1,1);

    System.out.println(tt.getName() + " " + tt.getSpareWheels());

Where car is interace that every Car ( SportCar, SlowCar, FastCar) implements.

However using this, i recieve null on every method call, e.g the print outputs null or 0

Why is this happening?

Thanks for help.





Aucun commentaire:

Enregistrer un commentaire