转自: http://blog.youkuaiyun.com/javadhh/article/details/24109561
- package com.chart.test;
- import java.beans.PropertyDescriptor;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- public class TestClass {
- public static void main(String[] args) {
- //Student(Integer id, String name, Integer age)
- Student stu = new Student(1, "张三", 25);
- System.out.println("通过对象获得类:"+stu.getClass()); //通过对象获得类
- System.out.println("==========================");
- System.out.println("得到类的父类:"+stu.getClass().getGenericSuperclass());
- System.out.println("==========================");
- method(stu); //结果 1 张三 25
- method(stu,"name"); //结果 张三
- }
- /**
- * 通过对象得到所有的该对象所有定义的属性值
- * @param obj 目标对象
- */
- public static void method(Object obj){
- try{
- Class clazz = obj.getClass();
- Field[] fields = obj.getClass().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 (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 通过对象和具体的字段名字获得字段的值
- * @param obj 目的对象
- * @param filed 字段名
- * @return 通过字段名得到字段值
- */
- public static Object method(Object obj,String filed) {
- try {
- Class clazz = obj.getClass();
- PropertyDescriptor pd = new PropertyDescriptor(filed,clazz);
- Method getMethod = pd.getReadMethod();//获得get方法
- Object o = getMethod.invoke(obj);//执行get方法返回一个Object
- return o;
- }catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- }