通过方法名调用方法 & 知道类名生成类

1.通过类名生成类

String className = "com.rongji.demo";//必须含有包

Object o = Class.forName(className).newInstance();//生成对应的类

2.通过方法名调用方法

String methodName = "setMethod";

Method m = o.getClass.getMethod(methodName,null);//得到方法 具体看API o这个对象的methodName这个方法,第二个参数需要输入参数类型 如果没有参数则为null

m.invoke(o,null);//调用方法 具体看API o这个对象调用m这个方法,没有参数所以为null

 

例子:

1.要调用的类 和方法

package classDemo;

public class NewClass {

public void newMethod(){
System.out.println("this is a method");
}

public NewClass() {
System.out.println("this is a Class");
}

}

2.生成类和调用其中的方法

public void createClass(){
String className = "classDemo.NewClass";
Object o = null;
String methodName = "newMethod";
try {
o = Class.forName(className).newInstance();
NewClass nc = (NewClass) o;
Method m = nc.getClass().getMethod(methodName, null);
// Method m = o.getClass().getMethod(methodName,o.getClass().getInterfaces()[0]);
m.invoke(o, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

posted @ 2014-04-11 12:59  刘尊礼  阅读(368)  评论(0)    收藏  举报