目標
Man類
Women類
代理類
package Reflect;
import java
public class Person { //代理類
private Object target; //目標對象
private String methodName; //目標方法
private Object[] params; //參數數組
private Method method;
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
thodName = methodName;
}
public Object[] getParams() {
return params;
}
public void setParams(Object[] params) {
this
}
public Person(){
}
/**
* _重新設置目標方法
*/
private void reSetMethod(String methodName){
if(params!=null){ //目標方法有參數
int paramsLength = params
Class<?>[] paramsTypes = new Class<?>[paramsLength];
for(int i=
paramsTypes[i] = params[i]
}
try {
method = target
} catch (SecurityException e) {
e
} catch (NoSuchMethodException e) {
e
}
}
else //目標方法參數為null
{
try {
method = target
} catch (SecurityException e) {
e
} catch (NoSuchMethodException e) {
e
}
}
}
/**
* _重新設置目標對象和方法
*/
private void reSetTarget(Object target
this
this
}
/**
* _動態調用已綁定方法
*/
public void doMethod() throws Exception{
reSetTarget(target
thod
}
}
調用示例
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25780.html