通過反射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()被調用過了!");
private String doPrivate() {
System.out.println("log: 私有方法lavasoft.test.MyService.doPrivate()被調用過了!");
return "私有方法doPrivate()被調用了!";
}
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.doSomething()被調用過了!
張三 is doing 吃飯! 附加消息:通過反射調用了sv對象上的一個方法!
log: 私有方法lavasoft.test.MyService.doPrivate()被調用過了!
log: lavasoft.test.MyService.getMsg()被調用過了!
hahahahahahahaha
Process finished with exit code 0
本文轉自 leizhimin 51CTO部落格,原文連結:http://blog.51cto.com/lavasoft/311484,如需轉載請自行聯系原作者