java 反射 測試

package com.test.unit.util;

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

/**
 * 反射相關函數
 * 
*/
public class AboutReflect {

    /**
     * 觸發對象方法
     * 
     * @param obj        方法所在對象
     * @param methodName 方法名
     * @param classes    參數類型
     * @param objects    參數
     * @return
     */
    public static Object invoke(final Object obj, final String methodName, final Class[] classes,
                                final Object[] objects) {
        try {
            Method method = getMethod(obj.getClass(), methodName, classes);
            method.setAccessible(true);
            return method.invoke(obj, objects);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 獲取對象的方法
     * 
     * @param classParam 方法存在的類對象
     * @param methodName 方法名
     * @param classes    參數類型
     * @return           該對象的方法
     * @throws Exception
     */
    public static Method getMethod(Class classParam, String methodName, final Class[] classes)
                                                                                              throws Exception {
        Method method = null;
        try {
            method = classParam.getDeclaredMethod(methodName, classes);
        } catch (NoSuchMethodException e) {
            try {
                method = classParam.getMethod(methodName, classes);
            } catch (NoSuchMethodException ex) {
                if (classParam.getSuperclass() == null) {
                    return method;
                } else {
                    method = getMethod(classParam.getSuperclass(), methodName, classes);
                }
            }
        }
        return method;
    }

    /**
     * 設置類對象中變量值
     * 
     * @param obj         需要設變量值的類對象
     * @param fieldName   變量值名
     * @param value       變量值
     */
    public static void setFiled(Object obj, String fieldName, Object value) {
        Class dc = obj.getClass();
        try {
            Field field = dc.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(obj, value);
        } catch (SecurityException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章