package kan.hui;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MainClass {
public static void main(String[] args) {
String className = "kan.hui.ClassOne";
className = "kan.hui.ClassTwo";
try{
//doIt(className);
doMethod(className);
}catch(Exception e){
System.out.println(e.toString());
}
}
public static void doIt(String className) throws InstantiationException, IllegalAccessException{
try {
Class cls = Class.forName(className);
//Object o = cls.newInstance();
InterfaceOne factory = (InterfaceOne)cls.newInstance();
factory.say();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void doMethod(String className) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
try {
Class cls = Class.forName(className);
InterfaceOne factory = (InterfaceOne)cls.newInstance();
Method mtd = finMain(cls);
mtd.invoke(factory, new Object[]{"Reflect String!"});
System.out.println(((ClassTwo)factory).getStr());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static Method finMain(Class toRun){
Method[] methods = toRun.getMethods();
for(Method method : methods){
if(method.getName().equals("setStr")){
return method;
}
}
return null;
}
}
参考:http://www.cppblog.com/baby-fly/archive/2011/02/27/140765.aspx
Java Class.forname
最新推荐文章于 2024-07-12 16:26:30 发布