package Demo;

/**
 * 在类UserInfo中有属性userName,我们可以通过getUserName和setUserName得到其值和设置新值
 * 通过getUserName/setUserName来访问userName属性,java JDK提供了一套api用来访问某个属性的getter/setter方法,这就是内省
 JDK内省类库:

PropertyDescriptor类:

PropertyDescriptor类表示JavaBean类通过存储器导出一个属性。主要方法:
 1. getPropertyType(),获得属性的Class对象;
 2. getReadMethod(),获得用于读取属性值的方法;getWriteMethod(),获得用于写入属性值的方法;
 3. hashCode(),获取对象的哈希值;
 4. setReadMethod(Method readMethod),设置用于读取属性值的方法;
 5. setWriteMethod(Method writeMethod),设置用于写入属性值的方法。
 
 Introspector 将javaBean中的属性封装起来进行操作。在程序中把一个类当做javaBean来看,就是调用Introspector的getBeanInfo(),得到BeanInfo对象封装了把这个类当做javaBean
 k看到的结果信息,既属性的信息
 getPropertyDescriptors()获得属性的描述,可以通过遍历beanInfo 方法来查找设置类的属性
 */
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BeanUtil {

public static void setProperty(UserInfo user)
throws IntrospectionException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {

PropertyDescriptor propDesc = new PropertyDescriptor("userName",
user.getClass());
Method writeMethod = propDesc.getWriteMethod();
writeMethod.invoke(user, "min");
System.out.println(user.getUserName());
}

public static void getProperty(UserInfo user) throws Exception {
PropertyDescriptor proDesc = new PropertyDescriptor("userName",
user.getClass());
Method readMethod = proDesc.getReadMethod();
Object userInfo = readMethod.invoke(user);
System.out.println(userInfo.toString());

}

public static void setPropertyByIntrospector(UserInfo user)
throws Exception {
BeanInfo beanInfo = Introspector.getBeanInfo(user.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo
.getPropertyDescriptors();
if (propertyDescriptors != null && propertyDescriptors.length > 0) {
for (PropertyDescriptor prodesc : propertyDescriptors) {
if (prodesc.getName().equals("userName")) {
Method writeMethod = prodesc.getWriteMethod();
writeMethod.invoke(user, "panmin");
System.out.println("set userName:" + user.getUserName());
break;
}

}
}
}
 public static void getPropertyByIntrospector(UserInfo user) throws Exception{
BeanInfo beanInfo = Introspector.getBeanInfo(user.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
if(propertyDescriptors!=null && propertyDescriptors.length>0){
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
Method readMethod = propertyDescriptor.getReadMethod();
Object object = readMethod.invoke(user);
System.out.println(object.toString());
}
}
 }
public static void main(String[] args) throws Exception {
UserInfo userInfo = new UserInfo();
setProperty(userInfo);
getProperty(userInfo);
}
}

以下例子是用的ListComparator排序
package com.letv.common.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Comparator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author zxwu
 */
public class ListDataComparator implements Comparator<Object> {

private Log logger = LogFactory.getLog(this.getClass());
    private String field;
    private boolean asc = false;
    public ListDataComparator(){
   
    }
    
    public ListDataComparator(String field){
    this.setField(field);
    }
    /**
     * @return the field
     */
    public String getField() {
        return field;
    }

/**
     * @param field the field to set
     */
    public void setField(String field) {
        this.field = field;
    }

/**
     * @return the asc
     */
    public boolean isAsc() {
        return asc;
    }

/**
     * @param asc the asc to set
     */
    public void setAsc(boolean asc) {
        this.asc = asc;
    }

@Override
    public int compare(Object o1, Object o2) {
        try {
            BeanInfo info = Introspector.getBeanInfo(o1.getClass());
            PropertyDescriptor[] props = info.getPropertyDescriptors();
            for (int i = 0; i < props.length; i++) {
                if (props[i].getName().equals(field)) {
                    Method method = props[i].getReadMethod();
                    try {
                        Integer f1 = (Integer) method.invoke(o1, new Object[0]);
                        Integer f2 = (Integer) method.invoke(o2, new Object[0]);
                        int result = f1.compareTo(f2);
                        if (isAsc()) {
                            return result;
                        } else {
                            if (result < 0) {
                                return 1;
                            } else if (result > 0) {
                                return -1;
                            }
                        }
                    } catch (java.lang.ClassCastException e) {
                        try {
                            Float f1 = (Float) method.invoke(o1, new Object[0]);
                            Float f2 = (Float) method.invoke(o2, new Object[0]);
                            int result = f1.compareTo(f2);
                            if (isAsc()) {
                                return result;
                            } else {
                                if (result < 0) {
                                    return 1;
                                } else if (result > 0) {
                                    return -1;
                                }
                            }
                        } catch (java.lang.ClassCastException e1) {
                            try {
                                String f1 = (String) method.invoke(o1, new Object[0]);
                                String f2 = (String) method.invoke(o2, new Object[0]);
                                int result = f1.compareTo(f2);
                                if (isAsc()) {
                                    return result;
                                } else {
                                    if (result < 0) {
                                        return 1;
                                    } else if (result > 0) {
                                        return -1;
                                    }
                                }
                            } catch (java.lang.ClassCastException e2) {
                                Long f1 = (Long) method.invoke(o1, new Object[0]);
                                Long f2 = (Long) method.invoke(o2, new Object[0]);
                                int result = f1.compareTo(f2);
                                if (isAsc()) {
                                    return result;
                                } else {
                                    if (result < 0) {
                                        return 1;
                                    } else if (result > 0) {
                                        return -1;
                                    }
                                }
                            }
                        }
                    }
                    break;
                }
            }
        } catch (Exception e) {
            logger.error(e, e);
        }
        return 0;
    }

}

/**
     * 对list对象中的id字段进行排序
     * 
     * @param list
     * @return
     */
    private List<T> getDescList(List<T> list) {
        ListDataComparator compare = new ListDataComparator("id");
        compare.setAsc(false);
        Collections.sort(list, compare);
        return list;
    }

PropertyDescriptor相关推荐

  1. 内省、JavaBean、PropertyDescriptor类、Introspector类、BeanUtils工具包、注解、Rentention、Target、注解的基本属性和高级属性...

    内省.JavaBean.PropertyDescriptor类.Introspector类.BeanUtils工具包.注解.Rentention.Target.注解的基本属性和高级属性 本文转载自:h ...

  2. java的自省机制_JAVA内省(自省)机制 ( Introspector , BeanInfo, PropertyDescriptor )

    目的和作用: 通过内省,获取和操作javaBean中的成员信息(方法,事件,属性). ------------------内省使用的核心类(接口)-------------------– Java.b ...

  3. java反射--PropertyDescriptor类:(属性描述器)、Introspector类

    JAVA中反射机制(JavaBean的内省与BeanUtils库) 内省(Introspector) 是Java 语言对JavaBean类属性.事件的一种缺省处理方法. JavaBean是一种特殊的类 ...

  4. java PropertyDescriptor 应用

    1. 概述 Java类中的私有的(private)属性是获取不到的(即使使用继承依然获取不到),那如果非要获取私有属性的值怎么办呢?一般的做法是将该java类封装称为一个JavaBean,即封装该私有 ...

  5. PropertyDescriptor 获取属性名称“aProp“ 为“AProp“问题分析

    项目场景: 使用java.bean.PropertyDescriptor相关的java.bean获取bean的属性 将map转换为bean 使用Spring BeanMap 获取bean信息 问题描述 ...

  6. java:PropertyDescriptor+反射调用setter方法

    java:PropertyDescriptor+反射调用setter方法 1 前言 PropertyDescriptor文档如下: https://docs.oracle.com/javase/7/d ...

  7. Java内省API PropertyDescriptor#createPropertyEditor(javaBean)返回null造成空指针

    问题描述 propertyDescriptor.setPropertyEditorClass(DatePropertyEditor.class);PropertyEditor propertyEdit ...

  8. java PropertyDescriptor的用法

    1.作用域 PropertyDescriptor中文叫属性描述器,是jiava JavaBean的内省与BeanUtils库 JavaBean是一种特殊的类,主要用于传递数据信息,这种类中的方法主要用 ...

  9. PropertyDescriptor 详解

    PropertyDescriptor 详解](http://blog.csdn.net/z69183787/article/details/8443777) 转自 http://blog.csdn.n ...

  10. Java中PropertyDescriptor用法

    PropertyDescriptor 类表示 JavaBean 类通过存储器导出一个属性. 构造方法有: PropertyDescriptor(String propertyName, Class&l ...

最新文章

  1. CentOS6.4 安装OpenResty和Redis 并在Nginx中利用lua简单读取Redis数据
  2. GraphQL 01--- GraphQL 介绍及资源总结
  3. 【转】你所不知道的HTML head/ 头标签
  4. 设计模式-结构型-适配器
  5. ML之NB:基于NB朴素贝叶斯算法训练20类新闻文本数据集进行多分类预测
  6. [J2ME QA]真机报告MontyThread -n的错误之解释
  7. sysbench压测服务器及结果解读(重点)
  8. 深度学习算法原理_用于对象检测的深度学习算法的基本原理
  9. 社区架构培训班四期开始报名了
  10. 比亚迪宋Plus DM-i值得买嘛?
  11. Django学习手册 - ORM sqlit基础数据库操作
  12. android 商品筛选_商品关联分析
  13. GRT上线Bancor提案已通过
  14. Python 模块(module)
  15. spring boot 在IDEA使用devtools热布署不成功,都没有注意的事!
  16. 算法:回溯十一 Subsets数组的子数组集合4种解法
  17. mariaDB数据库安装
  18. Elasticsearch面试专题总结
  19. 多种隐藏滚动条但是依然可以滚动实现方式
  20. 天龙单机服务器维护,天龙八部网游单机服务器修改资料(Dragon eight online games, single server, modify information).doc...

热门文章

  1. CentOS7上安装linux QQ
  2. 保健品推荐一(男性篇)
  3. Msfvenom介绍及利用
  4. 如何监控NVIDIA GPU 的运行状态和使用情况
  5. Flash移动开发高级教程——创建Anroid iPhone应用
  6. 2008年湖南省计算机应用技能竞赛-考试内容
  7. 字节跳动开源其云原生数据仓库 ByConity
  8. 电脑cpu占用率高?怎么办?1分钟快速解决!
  9. 【2017下集美大学软工1412班_助教博客】个人作业1——四则运算题目生成程序 成绩公示...
  10. Talib指标公式及释义整理