- 相關(guān)推薦
SUN認(rèn)證考試知識(shí)點(diǎn):Java反射機(jī)制的應(yīng)用
目標(biāo):用一個(gè)代理類實(shí)現(xiàn)兩個(gè)相似類的調(diào)用
1.兩個(gè)相似類
Man類
Women類:
代理類:
package Reflect;
import java.lang.reflect.Method;
public class Person { //代理類
private Object target; //目標(biāo)對(duì)象
private String methodName; //目標(biāo)方法
private Object[] params; //參數(shù)數(shù)組
private Method method;
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this.target = target;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public Object[] getParams() {
return params;
}
public void setParams(Object[] params) {
this.params = params;
}
public Person(){
}
/**
* _重新設(shè)置目標(biāo)方法
*/
private void reSetMethod(String methodName){
if(params!=null){ //目標(biāo)方法有參數(shù)
int paramsLength = params.length;
Class[] paramsTypes = new Class[paramsLength];
for(int i=0;i
paramsTypes[i] = params[i].getClass();
}
try {
method = target.getClass().getMethod(methodName,paramsTypes);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
else //目標(biāo)方法參數(shù)為null
{
try {
method = target.getClass().getMethod(methodName,null);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
/**
* _重新設(shè)置目標(biāo)對(duì)象和方法
*/
private void reSetTarget(Object target,String methodName){
this.target = target;
this.reSetMethod(methodName);
}
/**
* _動(dòng)態(tài)調(diào)用已綁定方法
*/
public void doMethod() throws Exception{
reSetTarget(target,methodName);
this.method.invoke(target, params);
}
}
【SUN認(rèn)證考試知識(shí)點(diǎn):Java反射機(jī)制的應(yīng)用】相關(guān)文章:
sun java認(rèn)證考試介紹10-23
Sun java認(rèn)證考試答案11-06
Sun Java認(rèn)證考試科目08-30
sun java認(rèn)證考試報(bào)考指南10-18
SUN JAVA認(rèn)證介紹08-09
SUN認(rèn)證考試知識(shí)點(diǎn):java servlet生命周期09-25