This is a follow up on this question: Create new class from a Variable in Java
I want to load a class based on a string variable which works, but I can't call any methods of it.
I have multiple classes that all implement the same interface, e.g.
class Foo implements Bar {
private String username = null;
public String getUsername() {
return this.username;
}
}
Now I want to instantiate the class without knowing which one it is, then call getUsername()
on it.
String a = "Foo";
Class<?> c = Class.forName(a);
Object object = c.newInstance();
System.out.println(object.getUsername());
This results in
Error:(74, 15) java: cannot find symbol
symbol: method getUser()
location: variable object of type java.lang.Object
If I cast it to the class like
Foo foo = (Foo) object;
it works, but I can't do that as I don't know the class' name.
Is there a way to do this or is this altogether a falsy attempt?