以前发过一个自己编写的通过类反射机制实现的非常好用的JAVA动态类处理源码,后来在网上又看到一个同样通过反射完成动态类处理的Java类,感觉在代码简洁与程序处理上都较我的强,就在其基础上做了些修改完善,共享给大家。

ClassReflect.java

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Java Reflection Cookbook
 *
 * @author Michael Lee
 * @author sidac modified at 2007-9-7
 * @since 2006-8-23
 * @version 0.1a
 */
public class ClassReflect {
 /**
  * 得到某个对象的公共属性
  * @param owner 对象
  * @param fieldName 属性
  * @return 该属性对象
  * @throws ReflectionErrorException 反射操作抛出例外
  */
 public static Object getProperty(Object owner, String fieldName) throws ReflectionErrorException{
  try {
   Class ownerClass = owner.getClass();
   Object property = null;
   try{
    //优先处理提供Getter方法的(非)公共属性(为POJO类的属性处理提供方便)
    property = invokeMethod(owner, "get" + upperFirstChar(fieldName), null);
   } catch (ReflectionErrorException e){
    //按Getter方法没提取到再按Public属性提取下
    Field field = ownerClass.getField(fieldName);
    property = field.get(owner);
   }

   return property;
  } catch (Exception e) {
   //May happen Exception:
   //SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException
   throw new ReflectionErrorException("Get object property error.", e);
  }
 }

 /**
  * 设置某个对象的公共属性
  * @param owner 对象
  * @param fieldName 属性
  * @param value 设置值
  * @return 该属性对象
  * @throws ReflectionErrorException 反射操作抛出例外
  */
 public static void setProperty(Object owner, String fieldName, Object value) throws ReflectionErrorException{
  try {
   Class ownerClass = owner.getClass();
   try{
    //优先处理提供Setter方法的(非)公共属性(为POJO类的属性处理提供方便)
    invokeMethod(owner, "set" + upperFirstChar(fieldName), new Object[]{value});
   } catch (ReflectionErrorException e){
    //按Getter方法没提取到再按Public属性提取下
    Field field = ownerClass.getField(fieldName);
    field.set(owner, value);
   }
  } catch (Exception e) {
   //May happen Exception:
   //SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException
   throw new ReflectionErrorException("Set object property error.", e);
  }
 }

 /**
  * 得到某类的静态公共属性
  * @param className 类名
  * @param fieldName 属性名
  * @return 该属性对象
  * @throws ReflectionErrorException 反射操作抛出例外
  */
 public static Object getStaticProperty(String className, String fieldName) throws ReflectionErrorException {
  try {
   Class ownerClass = Class.forName(className);
   
   Field field = ownerClass.getField(fieldName);
   Object property = field.get(ownerClass);

   return property;
  } catch (Exception e) {
   //May happen Exception:
   //ClassNotFoundException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException
   throw new ReflectionErrorException("Get static object property error.", e);
  }
 }

 /**
  * 执行某对象方法
  * @param owner 对象
  * @param methodName 方法名
  * @param args 参数
  * @return 方法返回值
  * @throws ReflectionErrorException 反射操作抛出例外
  */
 public static Object invokeMethod(Object owner, String methodName, Object[] args) throws ReflectionErrorException {
  try {
   Class ownerClass = owner.getClass();
   Method method = null;
   if(args == null) {
    method = ownerClass.getMethod(methodName, null);
   } else {
    Class[] argsClass = new Class[args.length];
    for (int i = 0, j = args.length; i < j; i++) {
     argsClass[i] = args[i].getClass();
    }
 
    method = ownerClass.getMethod(methodName, argsClass);
   }
   
   return method.invoke(owner, args);
  } catch (Exception e) {
   //May happen Exception:
   //SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
   throw new ReflectionErrorException("Invoke object method error.", e);
  }
 }

 /**
  * 执行某类的静态方法
  * @param className 类名
  * @param methodName 方法名
  * @param args 参数数组
  * @return 执行方法返回的结果
  * @throws ReflectionErrorException 反射操作抛出例外
  */
 public static Object invokeStaticMethod(String className, String methodName, Object[] args) throws ReflectionErrorException {
  try {
   Class ownerClass = Class.forName(className);
   Method method = null;
   if(args == null) {
    method = ownerClass.getMethod(methodName, null);
   } else {
    Class[] argsClass = new Class[args.length];
    for (int i = 0, j = args.length; i < j; i++) {
     argsClass[i] = args[i].getClass();
    }

    method = ownerClass.getMethod(methodName, argsClass);
   }
   
   return method.invoke(null, args);
  } catch (Exception e) {
   //May happen Exception:
   //ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
   throw new ReflectionErrorException("Invoke static object method error.", e);
  }
 }

 /**
  * 新建类实例
  * @param className 类名
  * @param args 构造函数的参数
  * @return 新建的实例
  * @throws ReflectionErrorException 反射操作抛出例外
  */
 public static Object newInstance(String className, Object[] args) throws ReflectionErrorException {
  try {
   Class newoneClass = Class.forName(className);

   Class[] argsClass = new Class[args.length];
   for (int i = 0, j = args.length; i < j; i++) {
    argsClass[i] = args[i].getClass();
   }

   Constructor cons = newoneClass.getConstructor(argsClass);
   return cons.newInstance(args);
  } catch (Exception e) {
   //May happen Exception:
   //ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException
   throw new ReflectionErrorException("Create new object instance error.", e);
  }
 }

 /**
  * 是不是某个类的实例
  * @param obj 实例
  * @param cls 类
  * @return 如果 obj 是此类的实例,则返回 true
  */
 public static boolean isInstance(Object obj, Class cls) {
  return cls.isInstance(obj);
 }

 /**
  * 得到数组中的某个元素
  * @param array 数组
  * @param index 索引
  * @return 返回指定数组对象中索引组件的值
  */
 public static Object getByArray(Object array, int index) {
  return Array.get(array, index);
 }
 
 /**
  * 大写单词首字母
  * @param str 单词
  * @return 大写首字母后的单词
  */
 public static String upperFirstChar(String str) {
  if (str == null || str.equals("")) {
   return str;
  } else {
   StringBuffer result = new StringBuffer(str.substring(0, 1).toUpperCase());
   result.append(str.substring(1).toLowerCase());
   return result.toString();
  }
 }
}

反射处理例外声明类
ReflectionErrorException.java

/**
 * @author sidac
 * Reflection 动态处理时错误时统一抛出的例外
 */
public class ReflectionErrorException extends Exception {
    /**
  *
  */
 private static final long serialVersionUID = 346011547748517512L;
 /**
  * throw Exception in the method RunClass of DynamicRunClass
  * when can't find the method to runed which the user specified
  */
 private Throwable ex;

    public ReflectionErrorException() {
     super((Throwable)null);  // Disallow initCause
    }

    public ReflectionErrorException(String s) {
     super(s, null);  //  Disallow initCause
    }

    public ReflectionErrorException(String s, Throwable ex) {
  super(s, null);  //  Disallow initCause
  this.ex = ex;
    }

    public Throwable getException() {
        return ex;
    }

    public Throwable getCause() {
        return ex;
    }
}

 

下面是原来的代码:

Java反射经典实例 Java Reflection Cookbook   <script src="" type=text/javascript></script>

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;


/**
 * Java Reflection Cookbook
 *
 * @author Michael Lee
 * @since 2006-8-23
 * @version 0.1a
 */

public class Reflection {
    /**
     * 得到某个对象的公共属性
     *
     * @param owner, fieldName
     * @return 该属性对象
     * @throws Exception
     *
     */
    public Object getProperty(Object owner, String fieldName) throws Exception {
        Class ownerClass = owner.getClass();

        Field field = ownerClass.getField(fieldName);

        Object property = field.get(owner);

        return property;
    }

    /**
     * 得到某类的静态公共属性
     *
     * @param className   类名
     * @param fieldName   属性名
     * @return 该属性对象
     * @throws Exception
     */
    public Object getStaticProperty(String className, String fieldName)
            throws Exception {
        Class ownerClass = Class.forName(className);

        Field field = ownerClass.getField(fieldName);

        Object property = field.get(ownerClass);

        return property;
    }


    /**
     * 执行某对象方法
     *
     * @param owner
     *            对象
     * @param methodName
     *            方法名
     * @param args
     *            参数
     * @return 方法返回值
     * @throws Exception
     */
    public Object invokeMethod(Object owner, String methodName, Object[] args)
            throws Exception {

        Class ownerClass = owner.getClass();

        Class[] argsClass = new Class[args.length];

        for (int i = 0, j = args.length; i < j; i++) {
            argsClass[i] = args[i].getClass();
        }

        Method method = ownerClass.getMethod(methodName, argsClass);

        return method.invoke(owner, args);
    }


      /**
     * 执行某类的静态方法
     *
     * @param className
     *            类名
     * @param methodName
     *            方法名
     * @param args
     *            参数数组
     * @return 执行方法返回的结果
     * @throws Exception
     */
    public Object invokeStaticMethod(String className, String methodName,
            Object[] args) throws Exception {
        Class ownerClass = Class.forName(className);

        Class[] argsClass = new Class[args.length];

        for (int i = 0, j = args.length; i < j; i++) {
            argsClass[i] = args[i].getClass();
        }

        Method method = ownerClass.getMethod(methodName, argsClass);

        return method.invoke(null, args);
    }



    /**
     * 新建实例
     *
     * @param className
     *            类名
     * @param args
     *            构造函数的参数
     * @return 新建的实例
     * @throws Exception
     */
    public Object newInstance(String className, Object[] args) throws Exception {
        Class newoneClass = Class.forName(className);

        Class[] argsClass = new Class[args.length];

        for (int i = 0, j = args.length; i < j; i++) {
            argsClass[i] = args[i].getClass();
        }

        Constructor cons = newoneClass.getConstructor(argsClass);

        return cons.newInstance(args);

    }


    
    /**
     * 是不是某个类的实例
     * @param obj 实例
     * @param cls 类
     * @return 如果 obj 是此类的实例,则返回 true
     */
    public boolean isInstance(Object obj, Class cls) {
        return cls.isInstance(obj);
    }
    
    /**
     * 得到数组中的某个元素
     * @param array 数组
     * @param index 索引
     * @return 返回指定数组对象中索引组件的值
     */
    public Object getByArray(Object array, int index) {
        return Array.get(array,index);
    }
}