I have class names unknown to my factory class that I obtained via runtime input.
Currently I have solution to use reflection to create instances of these classes in my factory class, but I want to see if it is possible to pass the method reference new
of these classes to my factory class so that I don't need to use reflection. e.g.:
public interface MyFactory {
MyClass getInstance(String s);
}
public static MyFactory getRuntimeClass(Class<? extends MyClass> cls) {
return cls::new;
}
public static void main(String[] args) {
MyClass mySubClass = getRuntimeClass(Class.forName(args[0]).asSubClass(MyClass.class)).getInstance("test");
}
The above does not work because the method reference new
is not obtainable from the Class object cls
.
How do you fix the above with method reference, without reverting back to use reflection?
P.S. Yes I have code to check the input, all the subclasses all have a constructor that takes a String as input.
Aucun commentaire:
Enregistrer un commentaire