使用反射调用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。这也就说明用此方法在做处理问题上的脆弱。

阅读更多
个人分类: JAVA
上一篇修改表结构的语句
下一篇oracle 主键/外键的操作
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭