使用反射调用set和get方法

package com.ksqqxq.utils;

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

/**
 * 
 * @author ksqqxq	
 * trigger setter or getter method by java refection
 * 
 **/

public class ReflectionUtils {

	private static ReflectionUtils instacnce = null;

	private ReflectionUtils() {

	}

	public static ReflectionUtils getInstance() {
		if (instacnce == null) {
			instacnce = new ReflectionUtils();
		}
		return instacnce;
	}

	/**
	 * @param : obj. the operating obj
	 * @param : attribute. the attribute you want to set
	 * */
	@SuppressWarnings("unchecked")
	private String invokeGetterMethod(Object obj, String attribute)throws Exception {

		Class clazz = obj.getClass();
		System.out.println(getMethodName(true,attribute));
		Method method = clazz.getMethod(getMethodName(true,attribute));
		
		return method.invoke(obj).toString();
	}
	
	/**
	 * @param : obj. the operating obj
	 * @param : attribute. the attribute you want to set
	 * @param : value. the value you want to set
	 * */
	@SuppressWarnings("unchecked")
	public void invokeSetterMethod(Object obj , String attribute, Object value) throws Exception{
		Class clazz = obj.getClass();
		Field field = clazz.getDeclaredField(attribute);
		Class paramType = field.getType();
		Method method = clazz.getMethod(getMethodName(false,attribute), paramType);
		method.invoke(obj, value);
		
	}
	
	/**
	 * @param : flag. which method you will get
	 * @param : attribute. which attribute you will get
	 * */
	private String getMethodName(boolean flag ,String attribute) {
		String firstElemntOfAttribute = attribute.substring(0, 1).toUpperCase();
		String restElementOfAttrute = attribute.substring(1);
		return (flag ? "get"  : "set")  +  firstElemntOfAttribute + restElementOfAttrute;
	}
	
}

注意:调用invokeGetMethod方法时,如果该对象对应的属性值为空时,会触发java.lang.NullPointerException。这也就说明用此方法在做处理问题上的脆弱。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值