Java反射工具类 枚举

反射工具类:调用Getter和Setter函数

public abstract class ReflectionUtil {

	private static final Log logger = LogFactory.getLog(ReflectionUtil.class);

	public static void setFieldValue(Object target, String fname,
			Class<?> ftype, Object fvalue) {
		setFieldValue(target, target.getClass(), fname, ftype, fvalue);
	}

	public static void setFieldValue(Object target, Class<?> clazz,
			String fname, Class<?> ftype, Object fvalue) {
		if (target == null
				|| fname == null
				|| "".equals(fname)) {
			return;
		}

		try {
			Method method = clazz.getDeclaredMethod(
					"set" + Character.toUpperCase(fname.charAt(0))
							+ fname.substring(1), ftype);
			// if (!Modifier.isPublic(method.getModifiers())) {
			method.setAccessible(true);
			// }
			method.invoke(target, fvalue);

		} catch (Exception me) {
			logger.error(me);
			try {
				Field field = clazz.getDeclaredField(fname);
				// if (!Modifier.isPublic(field.getModifiers())) {
				field.setAccessible(true);
				// }
				field.set(target, fvalue);
			} catch (Exception fe) {
				logger.error(fe);
			}
		}
	}

	public static Object getFieldValue(Object target, String fname) {
		return getFieldValue(target, target.getClass(), fname);
	}

	public static Object getFieldValue(Object target, Class<?> clazz,
			String fname) {
		if (target == null || fname == null || "".equals(fname)) {
			return null;
		}

		boolean exCatched = false;
		try {
			String methodname = "get" + StringUtils.capitalize(fname);
			Field field = clazz.getDeclaredField(fname);
			if (field.getClass().equals(boolean.class)) {
				methodname = "is" + StringUtils.capitalize(fname);
			}
			Method method = clazz.getDeclaredMethod(methodname);

			// if (!Modifier.isPublic(method.getModifiers())) {
			method.setAccessible(true);
			// }
			return method.invoke(target);
		} catch (NoSuchMethodException e) {
			exCatched = true;
		} catch (InvocationTargetException e) {
			exCatched = true;
		} catch (IllegalAccessException e) {
			exCatched = true;
		} catch (SecurityException e) {
			exCatched = true;
		} catch (NoSuchFieldException e) {
			exCatched = true;
		}

		if (exCatched) {
			try {
				Field field = clazz.getDeclaredField(fname);
				// if (!Modifier.isPublic(field.getModifiers())) {
				field.setAccessible(true);
				// }
				return field.get(target);
			} catch (Exception fe) {
				logger.error(fe);
			}
		}
		return null;
	}
}

反射+枚举应用:序列化、反序列化

//枚举类成员变量的名需要和要序列化、反序列化类里的成员变量名一致
public enum TestEnum {
    score(int.class),
    value,
    flag(boolean.class);

    private Class type;

    public Class getType() {
        return type;
    }

    public void setType(Class type) {
        this.type = type;
    }

    TestEnum() {
        this.type = String.class;
    }

    TestEnum(Class type) {
        this.type = type;
    }
}
public class TestClass {
    private String name;
    private int score;
    private String value;
    private boolean flag;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }


    //序列化
    public String toParamString(String SPLIT) {
        StringBuilder sb = new StringBuilder();
        TestEnum[] fs = TestEnum.values();
        for (TestEnum field : fs) {
            String name = field.name();
            Object res = ReflectionUtil.getFieldValue(this, name);
            if (res != null && !"null".equals(res)) {
                sb.append(res);
            }
            sb.append(SPLIT);
        }
        return sb.toString();
    }


    //反序列化
    public void ExtParam(String[] params) {
        TestEnum[] e = TestEnum.values();
        for (int i = 0; i < e.length; i++) {
            Object value = ConvertUtils.convert(params[i], e[i].getType());
            ReflectionUtil.setFieldValue(this, e[i].name(), e[i].getType(), value);
        }
    }

    //测试
    public static void main(String[] args) {
        TestClass test = new TestClass();
        test.setName("test~");
        test.setScore(123);
        test.setValue("reflect");
        test.setFlag(false);
        System.out.println(test.toParamString("%%%"));
        test.ExtParam("333%%%bbb%%%true".split("%%%"));
        System.out.println(test.toParamString("%%%"));
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值