I want to dynamically load a concrete class which implements an interface. Input: concrete class name.
开发者_Go百科I need to call a method in this concrete class, that is, I'll need to set:
MyInterface myclass = new concreteClassName();
myclass.function();
How can I achieve this?
have a look at Class.forName(String)
String str = "Test$B"; //your full class name here instead of Test$B
A clazz = null; //change A to be your interface
try {
clazz = (A)Class.forName(str).newInstance(); //change A to be your interface
} catch (Exception e) {
//TODO: handle exceptions
e.printStackTrace();
}
if (clazz != null) {
clazz.foo();
}
Have you checked out
try {
// Load class
Class<?> cls = Class.forName("my.package.ConcreteClass");
// Instantiate object from class using default constructor
my.package.ConcreteClass obj = (my.package.ConcreteClass) cls.newInstance();
// Execute method on it
obj.myMethod();
} catch (Exception e) {
throw new RuntimeException("Could not instantiate class", e);
}
and the respective javadoc entries for Class#forName
and Class#newInstance
?
You should implement your own ClassLoader.
精彩评论