通過反射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()被調用了!";
}
}
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);
m_setMsg.invoke(sv,"通過反射調用了sv對象上的一個方 法!");
Method m_do = clazz.getMethod ("doSomething",String.class ,String.class);
String re = (String)m_do.invoke(sv,"張三" ,"吃 飯");
System.out.println(re);
//通過反射方式調用對象的private方法
Method m_doPrivate = clazz.getDeclaredMethod ("doPrivate");
m_doPrivate.setAccessible(true);
m_doPrivate.invoke(sv);
//通過反射方式訪問對象private字段
Field f_msg = clazz.getDeclaredField("msg");
f_msg.setAccessible(true);
f_msg.set(sv,"hahahahahahahaha");
System.out.println(sv.getMsg());
}
}
log: 無參構造方法lavasoft.test.MyService.MyService()被調用過了!
log: lavasoft.test.MyService.setMsg()被調用過了!
log: lavasoft.test.MyService.setMsg()被調用過了!
log: 業務方法lavasoft.test.MyService.doSomething()被調用過了!
張三 is doing 吃飯! 附加消息:通過反射調用了sv對象上的一個方法!
log: 私有方法lavasoft.test.MyService.doPrivate()被調用過了!
log: lavasoft.test.MyService.getMsg()被調用過了!
hahahahahahahaha
Process finished with exit code 0
出處http://lavasoft.blog.51cto.com/62575/311484