通过PropertyDescriptor反射进行字段名值的获取及设置


/**
 * 根据属性名获取对应的value
 * @param fieldName
 * @param obj
 * @return
 * @throws Exception
 */
private static String getValueByFiled(String fieldName,Object obj)throws Exception{
       //属性扫描器
        PropertyDescriptor pd = new PropertyDescriptor(fieldName, obj.getClass());
        //从属性描述器中获取 get 方法
        Method method = pd.getReadMethod();
        //结果
        Object value = method.invoke(obj);
        //执行方法并返回结果
        return value==null?"":String.valueOf(value);
}

   

下面是比较完整的


public class PropertyUtil {  
    @SuppressWarnings("unchecked")  
    public static PropertyDescriptor getPropertyDescriptor(Class clazz, String propertyName) {  
        StringBuffer sb = new StringBuffer();//构建一个可变字符串用来构建方法名称  
        Method setMethod = null;  
        Method getMethod = null;  
        PropertyDescriptor pd = null;  
        try {  
            Field f = clazz.getDeclaredField(propertyName);//根据字段名来获取字段  
            if (f!= null) {  
                //构建方法的后缀  
               String methodEnd = propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);  
               sb.append("set" + methodEnd);//构建set方法  
               setMethod = clazz.getDeclaredMethod(sb.toString(), new Class[]{ f.getType() });  
               sb.delete(0, sb.length());//清空整个可变字符串  
               sb.append("get" + methodEnd);//构建get方法  
               //构建get 方法  
               getMethod = clazz.getDeclaredMethod(sb.toString(), new Class[]{ });  
               //构建一个属性描述器 把对应属性 propertyName 的 get 和 set 方法保存到属性描述器中  
               pd = new PropertyDescriptor(propertyName, getMethod, setMethod);  
            }  
        } catch (Exception ex) {  
                ex.printStackTrace();  
        }  
      
        return pd;  
    }  
    //对obj对象的指定字段进行值设置
    @SuppressWarnings("unchecked")  
    public static void setProperty(Object obj,String propertyName,Object value){  
        Class clazz = obj.getClass();//获取对象的类型  
        PropertyDescriptor pd = getPropertyDescriptor(clazz,propertyName);//获取 clazz 类型中的 propertyName 的属性描述器  
        Method setMethod = pd.getWriteMethod();//从属性描述器中获取 set 方法  
        try {  
            setMethod.invoke(obj, new Object[]{value});//调用 set 方法将传入的value值保存属性中去  
        }catch (Exception e){  
            e.printStackTrace();  
        }  
    }  
    
    //根据属性字段及对象获取对应的属性值	
    @SuppressWarnings("unchecked")  
    public static Object getProperty(Object obj, String propertyName){  
       Class clazz = obj.getClass();//获取对象的类型  
       PropertyDescriptor pd = getPropertyDescriptor(clazz,propertyName);//获取 clazz 类型中的 propertyName 的属性描述器  
       Method getMethod = pd.getReadMethod();//从属性描述器中获取 get 方法  
       Object value =null ;  
       try {  
           value = getMethod.invoke(clazz, new Object[]{});//调用方法获取方法的返回值  
       } catch (Exception e) {  
           e.printStackTrace();  
       }  
       return value;//返回值  
    }  
}  


//调用

import java.beans.PropertyDescriptor;  
import java.lang.reflect.Field;  
import java.lang.reflect.Method;  
public class ReflectTest {  
   
 public static void main(String[] args) throws Exception {  
  Class clazz = Class.forName("TaskProvidePropsList");//这里的类名是全名。。有包的话要加上包名  
  Object obj = clazz.newInstance();  
  Field[] fields = clazz.getDeclaredFields();  
  //写数据  
  for(Field f : fields) {  
   PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);  
   Method wM = pd.getWriteMethod();//获得写方法  
   wM.invoke(obj, 2);//因为知道是int类型的属性,所以传个int过去就是了。。实际情况中需要判断下他的参数类型  
  }  
  //读数据  
  for(Field f : fields) {  
   PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);  
   Method rM = pd.getReadMethod();//获得读方法  
   Integer num = (Integer) rM.invoke(obj);//因为知道是int类型的属性,所以转换成integer就是了。。也可以不转换直接打印  
   System.out.println(num);  
  }  
 }  
}  


参考:http://blog.csdn.net/qq_34120041/article/details/53665526






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: PropertyDescriptor类是Java中的一个类,用于描述JavaBean中的属性。它提供了访问属性的方法,包括获取属性的名称、类型、读写方法等。通过使用PropertyDescriptor类,可以方便地操作JavaBean中的属性,实现属性的读取、设置和监听等功能。在Java中,PropertyDescriptor类常用于JavaBean的反射操作和属性编辑器的实现。 ### 回答2: PropertyDescriptor 类是 Java 中的一个类,主要用于对某个属性进行操作和控制。它提供了一种机制,可以通过反射的方式获取设置一个类的属性的详细信息。 PropertyDescriptor 类提供了一系列的方法,例如: - getName()方法用于获取属性的名称; - getPropertyType()方法用于获取属性的类型; - getReadMethod()方法用于获取属性的读方法(getter方法); - getWriteMethod()方法用于获取属性的写方法(setter方法); - getValue()方法用于获取属性的; - setValue()方法用于设置属性的。 通过这些方法,可以灵活地对属性进行操作,例如获取属性的名称和类型,获取属性的读写方法,以及获取设置属性的PropertyDescriptor 类在 Java Beans 中广泛应用,特别是在图形界面编程中。它可以用于动态地操作和更新界面上的组件,例如文本框、标签等,使得界面的显示和交互更加灵活和便捷。 总的来说,PropertyDescriptor 类提供了一种方便的机制,可以通过反射的方式对类的属性进行操作和控制。它可以用于获取属性的名称和类型,以及获取设置属性的读写方法和。通过这些方法,可以在编码过程中更加灵活地对属性进行操作和管理,提高代码的可读性和可维护性。 ### 回答3: PropertyDescriptor类是Java中用来描述Java Bean中的属性的类。它提供了一种方便的方式来获取设置Java Bean中的属性PropertyDescriptor类可以通过传入属性名称和Java Bean的类对象来实例化。通过PropertyDescriptor实例化对象后,我们可以使用其提供的方法来获取设置属性的。 通过getPropertyType()方法,我们可以获取属性的类型。通过getReadMethod()方法和getWriteMethod()方法,我们可以获取属性的读取和设置方法。 除了获取设置属性的外,PropertyDescriptor类还可以用来操作Java Bean中的属性。通过setBound()方法,我们可以将属性绑定到一个属性编辑器,用于自定义属性的编辑器。通过setConstrained()方法,我们可以将属性标记为受约束属性,当属性发生改变时,可以触发PropertyChangeEvent事件。 PropertyDescriptor类提供了一种方便、灵活的方式来操作Java Bean中的属性,我们可以通过它来获取设置属性的,或者操作属性的绑定和约束。它是Java中处理Java Bean属性的重要工具之一。 总结起来,PropertyDescriptor类是用于描述Java Bean中属性的类,提供了获取设置属性的方法,可以操作属性的绑定和约束。它是Java中处理Java Bean属性的重要工具之一。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值