Java反射深度测试
时间:2011-09-14 51cto博客 leizhimin
通过反射API构造对象,并使用反射调用方式访问对象的public/private方法和字段。
package lavasoft.test;
/**
* 测试的业务类
*
* @author leizhimin 2010-5-6 20:16:10
*/
public class MyService {
private String msg;
public MyService() {
System.out.println("log: 无参构造方法 lavasoft.test.MyService.MyService()被调用过了!");
}
public MyService(String msg) {
System.out.println("log: 有参构造方法 lavasoft.test.MyService.MyService()被调用过了!");
this.msg = msg;
}
public String doSomething(String person, String something) {
System.out.println("log: 业务方法 lavasoft.test.MyService.doSomething()被调用过了!");
return person + " is doing " + something + "! " +
"附加消息:" + msg;
}
public String getMsg() {
System.out.println("log: lavasoft.test.MyService.getMsg ()被调用过了!");
return msg;
}
public void setMsg(String msg) {
System.out.println("log: lavasoft.test.MyService.setMsg ()被调用过了!");
this.msg = msg;
}
private String doPrivate() {
System.out.println("log: 私有方法 lavasoft.test.MyService.doPrivate()被调用过了!");
return "私有方法doPrivate()被调用了!";
}
}
Java反射深度测试(2)
时间:2011-09-14 51cto博客 leizhimin
package lavasoft.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.*;
/**
* Java反射深度测试
*
* @author leizhimin 2010-5-6 20:26:49
*/
public class TestReflect {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchFieldException {
//通过反射方式创建对象
Class clazz = MyService.class;
MyService sv = (MyService)clazz.getConstructor ().newInstance();
sv.setMsg("通过Class方式创建一个对象,并调用对象上的方法 !");
//通过反射方式调用对象的public方法
Method m_setMsg = clazz.getMethod ("setMsg",String.class);
|