java 反射通过get方法获得属性值

废弃


注意:类需要public访问权限,否则会报错


1、根据对象获得所有字段的值

public static void method(Object obj) {
	try {
		Class clazz = obj.getClass();
		Field[] fields = clazz.getDeclaredFields();// 获得属性
		for (Field field : fields) {
			PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
			Method getMethod = pd.getReadMethod();// 获得get方法
			Object o = getMethod.invoke(obj);// 执行get方法返回一个Object
			System.out.println(o);
		}
	} catch (SecurityException e) {
		e.printStackTrace();
	} catch (IllegalArgumentException e) {
		e.printStackTrace();
	} catch (IntrospectionException e) {
		e.printStackTrace();
	} catch (IllegalAccessException e) {
		e.printStackTrace();
	} catch (InvocationTargetException e) {
		e.printStackTrace();
	}
}




2、通过对象和具体的字段名字获得字段的值

public static void method(Object obj, String filed) {
	try {
		Class clazz = obj.getClass();
		PropertyDescriptor pd = new PropertyDescriptor(filed, clazz);
		Method getMethod = pd.getReadMethod();// 获得get方法

		if (pd != null) {

			Object o = getMethod.invoke(obj);// 执行get方法返回一个Object
			System.out.println(o);

		}
	} catch (SecurityException e) {
		e.printStackTrace();
	} catch (IllegalArgumentException e) {
		e.printStackTrace();
	} catch (IntrospectionException e) {
		e.printStackTrace();
	} catch (IllegalAccessException e) {
		e.printStackTrace();
	} catch (InvocationTargetException e) {
		e.printStackTrace();
	}
}




原文出处:/show_3334264d1b8643bcaca6704aa1851a4c.html