1. 程式人生 > >java反射輔助類

java反射輔助類


package com.cloudtech.web.util;
 
import java.lang.reflect.Field;
import java.util.ArrayList;

import com.cloudtech.web.entity.RuleCode;
 
public class ReflectUtil {
 
    /**
     * 使用反射設定變數值
     *
     * @param target 被呼叫物件
     * @param fieldName 被呼叫物件的欄位,一般是成員變數或靜態變數,不可是常量!
     * @param value 值
     * @param <T> value型別,泛型
     */
    public static <T> void setValue(Object target,String fieldName,T value) {
        try {
            Class c = target.getClass();
            Field f = c.getDeclaredField(fieldName);
            f.setAccessible(true);
            f.set(target, value);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 使用反射獲取變數值
     *
     * @param target 被呼叫物件
     * @param fieldName 被呼叫物件的欄位,一般是成員變數或靜態變數,不可以是常量
     * @param <T> 返回型別,泛型
     * @return 值
     */
    public static <T> T getValue(Object target,String fieldName) {
        T value = null;
        try {
            Class c = target.getClass();
            Field f = c.getDeclaredField(fieldName);
            f.setAccessible(true);
            value = (T) f.get(target);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return value;
    }
    
    public static void main(String[] args) {
		RuleCode code = new RuleCode();
		code.setId(1234);
		//Object value = ReflectUtil.getValue(code, "id");
		System.out.println(code.getId());
    /*	String s ="avgSpd gt hThreeMaxSpd";
    	String replace = s.replace("gt", "");
    	String[] split = replace.split(" ");
    	System.out.println();*/
	}
}