Java 反射工具類

eg756 9年前發布 | 5K 次閱讀 Java

package com.su.dolphin.utils;

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

/**

  • @className: ReflectionUtil
  • @description: 反射工具類
  • @author: gaoshuai
  • @date: 2015年8月5日 下午4:51:49 */ public class ReflectionUtil { /**

    • @title: setField
    • @description: 設置某個成員遍歷的值
    • @param owner
    • @param fieldName
    • @param value
    • @throws Exception
    • @return: void */ public static void setField(Object owner, String fieldName, Object value) throws Exception { Class<?> ownerClass = owner.getClass(); Field field = ownerClass.getDeclaredField(fieldName); field.setAccessible(true); field.set(owner, value); }

      /**

    • @title: setFieldAll
    • @description: 可以設置父類的field的值
    • @param owner
    • @param fieldName
    • @param value
    • @throws Exception
    • @return: void */ public static void setFieldAll(Object owner, String fieldName, Object value) throws Exception { Class<?> ownerClass = owner.getClass(); Field field = null; for (Class<?> clazz = ownerClass; clazz != Object.class; clazz = clazz.getSuperclass()) {

       try {
           field = clazz.getDeclaredField(fieldName);
           LogUtil.d(field + " find : in " + clazz.getName());
           break;
       }
       catch (Exception e) {
           LogUtil.d(fieldName + " not find in " + clazz.getName());
       }
      

      } field.setAccessible(true); field.set(owner, value); }

      /**

    • 得到某個對象的公共屬性
    • @param owner
    • , fieldName
    • @return 該屬性對象
    • @throws Exception
    • */ public static Object getField(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 static Object getStaticField(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 static 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++) {

       if (args[i].getClass() == Integer.class) { //一般的函數都是 int 而不是Integer
           argsClass[i] = int.class;
       }
       else if (args[i].getClass() == Float.class) { //一般的函數都是 int 而不是Integer
           argsClass[i] = float.class;
       }
       else if (args[i].getClass() == Double.class) { //一般的函數都是 int 而不是Integer
           argsClass[i] = double.class;
       }
       else {
           argsClass[i] = args[i].getClass();
       }
      

      }

      Method method = ownerClass.getDeclaredMethod(methodName, argsClass); method.setAccessible(true); return method.invoke(owner, args); }

      /**

    • @title: invokeMethodAll
    • @description: 調用所有的函數, 包括父類的所有函數
    • @param owner
    • @param methodName
    • @param args
    • @return
    • @throws Exception
    • @return: Object */ public static Object invokeMethodAll(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++) {

       if (args[i].getClass() == Integer.class) { //一般的函數都是 int 而不是Integer
           argsClass[i] = int.class;
       }
       else if (args[i].getClass() == Float.class) { //一般的函數都是 int 而不是Integer
           argsClass[i] = float.class;
       }
       else if (args[i].getClass() == Double.class) { //一般的函數都是 int 而不是Integer
           argsClass[i] = double.class;
       }
       else {
           argsClass[i] = args[i].getClass();
       }
      

      } Method method = null;

      for (Class<?> clazz = ownerClass; clazz != Object.class; clazz = clazz.getSuperclass()) {

       try {
           method = clazz.getDeclaredMethod(methodName, argsClass);
           LogUtil.d(method + " find : in " + clazz.getName());
           return method;
       }
       catch (Exception e) {
           //e.printStackTrace();
           LogUtil.d(methodName + " not find in " + clazz.getName());
       }
      

      } method.setAccessible(true); return method.invoke(owner, args); }

      /**

    • 執行某類的靜態方法
    • @param className
    • 類名
    • @param methodName
    • 方法名
    • @param args
    • 參數數組
    • @return 執行方法返回的結果
    • @throws Exception */ public static 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); method.setAccessible(true); return method.invoke(null, args); }

      /**

    • 新建實例
    • @param className
    • 類名
    • @param args
    • 構造函數的參數 如果無構造參數,args 填寫為 null
    • @return 新建的實例
    • @throws Exception */ public static Object newInstance(String className, Object[] args) throws NoSuchMethodException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { return newInstance(className, args, null);

      }

      /**

    • 新建實例
    • @param className
    • 類名
    • @param args
    • 構造函數的參數 如果無構造參數,args 填寫為 null
    • @return 新建的實例
    • @throws Exception */ public static Object newInstance(String className, Object[] args, Class<?>[] argsType) throws NoSuchMethodException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class<?> newoneClass = Class.forName(className);

      if (args == null) {

       return newoneClass.newInstance();
      
      

      } else {

       Constructor<?> cons;
       if (argsType == null) {
           Class<?>[] argsClass = new Class[args.length];
      
           for (int i = 0, j = args.length; i < j; i++) {
               argsClass[i] = args[i].getClass();
           }
      
           cons = newoneClass.getConstructor(argsClass);
       }
       else {
           cons = newoneClass.getConstructor(argsType);
       }
       return cons.newInstance(args);
      

      }

      }

      /**

    • 是不是某個類的實例
    • @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 getItemInArray(Object array, int index) { return Array.get(array, index); }

      /**

    • @title: GetClassListByPackage
    • @description: 獲取包下的所有Class
    • @param pPackage
    • @return
    • @return: Class<?> */ public static Class<?> getClassListByPackage(String pPackage) { Package _Package = Package.getPackage(pPackage); Class<?> _List = _Package.getClass();

      return _List; } }</pre>

      注意: 

      1.調用getMethods方法輸出的是自身的public方法和父類Object的public方法。調用getDeclaredMethods方法輸出的是自身的public、protected、private方法。

      2.如果想獲取父類的私有函數

      public static Method getDeclaredMethod(Object object, String methodName, Class<?> ... parameterTypes){
      Method method = null ;

      for(Class<?> clazz = object.getClass() ; clazz != Object.class ; clazz = clazz.getSuperclass()) {
      try {

       method = clazz.getDeclaredMethod(methodName, parameterTypes) ;  
       return method ;  
      

      } catch (Exception e) {
      }
      }

      return null;
      }</pre>
      來自:http://my.oschina.net/sfshine/blog/488280

 本文由用戶 eg756 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!