熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java反射機制的應用例子

2022-06-13   來源: Java核心技術 

  目標用一個代理類實現兩個相似類的調用

  兩個相似類

  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);

  }

  }

  調用示例

  


From:http://tw.wingwit.com/Article/program/Java/hx/201311/25780.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.