SUN认证考试知识点:Java反射机制的应用

2016-10-31 00:00:00嘉辉 SUN认证

  目标:用一个代理类实现两个相似类的调用

  1.两个相似类

  Man类

  Women类:

  代理类:

  package Reflect;

  import java.lang.reflect.Method;

  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.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(){

  }

  /**

  * _重新设置目标方法

  */

  private void reSetMethod(String methodName){

  if(params!=null){ //目标方法有参数

  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 //目标方法参数为null

  {

  try {

  method = target.getClass().getMethod(methodName,null);

  } catch (SecurityException e) {

  e.printStackTrace();

  } catch (NoSuchMethodException e) {

  e.printStackTrace();

  }

  }

  }

  /**

  * _重新设置目标对象和方法

  */

  private void reSetTarget(Object target,String methodName){

  this.target = target;

  this.reSetMethod(methodName);

  }

  /**

  * _动态调用已绑定方法

  */

  public void doMethod() throws Exception{

  reSetTarget(target,methodName);

  this.method.invoke(target, params);

  }

  }

[SUN认证]相关推荐

[SUN认证]相关栏目推荐
查看更多
上一篇:Java中接口的使用 下一篇:Java方法(函数)传值和传引用的问题