Java反射獲取對象屬性 以及值


import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 反射工具類
 */
public class ReflectionUtil {

	/**
	 * 通過屬性名稱獲得屬性值
	 * 
	 * @param object
	 * @param propertyName
	 * @return
	 */
	public static Object getValue(Object object, String propertyName) {
		try {
			Class<? extends Object> clazz = object.getClass();
			PropertyDescriptor pd = new PropertyDescriptor(propertyName, clazz);
			Method getMethod = pd.getReadMethod();// 獲得get方法
			Object o = getMethod.invoke(object);// 執行get方法返回一個Object
			return o;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 根據對象獲得所有字段的值
	 * 
	 * @param object
	 */
	public static void method(Object object) {
		try {
			Class<? extends Object> clazz = object.getClass();
			Field[] fields = object.getClass().getDeclaredFields();// 獲得屬性
			for (Field field : fields) {
				PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
				Method getMethod = pd.getReadMethod();// 獲得get方法
				Object o = getMethod.invoke(object);// 執行get方法返回一個Object
				System.out.println(o);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

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