目标用一个代理类实现两个相似类的调用
两个相似类
Man类
Women类
代理类
package Reflect;
import javalangreflectMethod;
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) {
thistarget = target;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
thodName = methodName;
}
public Object[] getParams() {
return params;
}
public void setParams(Object[] params) {
thisparams = params;
}
public Person(){
}
/**
* _重新设置目标方法
*/
private void reSetMethod(String methodName){
if(params!=null){ //目标方法有参数
int paramsLength = paramslength;
Class<?>[] paramsTypes = new Class<?>[paramsLength];
for(int i=;i<paramsLength;i++){
paramsTypes[i] = params[i]getClass();
}
try {
method = targetgetClass()getMethod(methodNameparamsTypes);
} catch (SecurityException e) {
eprintStackTrace();
} catch (NoSuchMethodException e) {
eprintStackTrace();
}
}
else //目标方法参数为null
{
try {
method = targetgetClass()getMethod(methodNamenull);
} catch (SecurityException e) {
eprintStackTrace();
} catch (NoSuchMethodException e) {
eprintStackTrace();
}
}
}
/**
* _重新设置目标对象和方法
*/
private void reSetTarget(Object targetString methodName){
thistarget = target;
thisreSetMethod(methodName);
}
/**
* _动态调用已绑定方法
*/
public void doMethod() throws Exception{
reSetTarget(targetmethodName);
thodinvoke(target params);
}
}
调用示例