java反射技术通过对象和属性名得到属性值

来源:互联网 发布:淘宝实木花架中式图片 编辑:程序博客网 时间:2024/06/05 06:42
[java] view plain copy
  1. package com.chart.test;  
  2. import java.beans.PropertyDescriptor;  
  3. import java.lang.reflect.Field;  
  4. import java.lang.reflect.Method;  
  5.   
  6. public class TestClass {  
  7.     public static void main(String[] args) {  
  8.         //Student(Integer id, String name, Integer age)  
  9.         Student stu = new Student(1"张三"25);  
  10.         System.out.println("通过对象获得类:"+stu.getClass());     //通过对象获得类  
  11.         System.out.println("==========================");  
  12.         System.out.println("得到类的父类:"+stu.getClass().getGenericSuperclass());  
  13.         System.out.println("==========================");  
  14.           
  15.         method(stu);   //结果  1  张三   25   
  16.         method(stu,"name");   //结果  张三  
  17.     }  
  18.       
  19.     /** 
  20.      * 通过对象得到所有的该对象所有定义的属性值 
  21.      * @param obj 目标对象 
  22.      */  
  23.     public static void method(Object obj){  
  24.        try{  
  25.            Class clazz = obj.getClass();  
  26.            Field[] fields = obj.getClass().getDeclaredFields();//获得属性  
  27.            for (Field field : fields) {  
  28.                PropertyDescriptor pd = new PropertyDescriptor(field.getName(),clazz);  
  29.                Method getMethod = pd.getReadMethod();//获得get方法  
  30.                Object o = getMethod.invoke(obj);//执行get方法返回一个Object  
  31.                System.out.println(o);  
  32.            }  
  33.        }catch (Exception e) {  
  34.            e.printStackTrace();  
  35.        }   
  36.      }  
  37.       
  38.     /** 
  39.      * 通过对象和具体的字段名字获得字段的值 
  40.      * @param obj 目的对象 
  41.      * @param filed 字段名 
  42.      * @return 通过字段名得到字段值 
  43.      */  
  44.     public static Object method(Object obj,String filed)   {  
  45.        try {  
  46.            Class clazz = obj.getClass();  
  47.            PropertyDescriptor pd = new PropertyDescriptor(filed,clazz);  
  48.            Method getMethod = pd.getReadMethod();//获得get方法  
  49.            Object o = getMethod.invoke(obj);//执行get方法返回一个Object  
  50.            return o;  
  51.        }catch (Exception e) {  
  52.            e.printStackTrace();  
  53.            return null;  
  54.        }   
  55.      }  
  56.       
  57. }  
0 0