java中使用反射机制获取实体类集合的某个属性值

来源:互联网 发布:linux scp定义算法 编辑:程序博客网 时间:2024/05/28 23:19

需求

今天遇到一个需求。需要从几个对象的集合中取出对象的某些属性。怎么办呢?哪就利用反射机制写个方法吧。

思路

入参

首先是几个对象的集合,那么方法的入参就是 list<?> 因为是不同对象所以还是得用泛型。用反射当然得有 参数Class<?> 最后还得有第三个参数就是需要获取的属性名。

出参

出参比较容易,就搞个String好了

实现

public static String getStringAbel(List<?> o, Class<?> c, String field) {        StringBuffer result = new StringBuffer();        if (StringUtils.isNoneBlank(field)) {            Field[] fields = c.getDeclaredFields();            int pos;            for (pos = 0; pos < fields.length; pos++) {                if (field.equals(fields[pos].getName())) {                    break;                }            }            for (Object o1 : o) {                try {                    fields[pos].setAccessible(true);                    result.append(fields[pos].get(o1) + ",");                } catch (Exception e) {                    System.out.println("error--------" + "Reason is:" + e.getMessage());                }            }        }        return result.deleteCharAt(result.length() - 1).toString();    }//调用  public static void main(String[] args) {        List<Person> personList = new ArrayList<>();        Person person = new Person();        person.setName("abel");        person.setAge(16);        Person person2 = new Person();        person2.setName("abel2");        person2.setAge(17);        personList.add(person);        personList.add(person2);        System.out.println(getStringAbel(personList, Person.class, "name"));    }

关于实现中的for 循环为什么不用 java8的 stream 呢?因为stream 就循环来说 和for 的效率大致差不多。反而 for 会使逻辑更清晰一点。stream 的优势在于对数据的分组,过滤,等方面。

具体观点请看:http://soujava.com/java8%E4%B8%AD%E4%BD%BF%E7%94%A8stream%E6%B5%81%E5%92%8Cfor%E5%BE%AA%E7%8E%AF%E5%88%86%E5%88%AB%E5%AF%B9%E6%95%B0%E6%8D%AE%E9%9B%86%E5%90%88%E9%81%8D%E5%8E%86%E7%9A%84%E5%B7%AE%E5%BC%82/

本文参考:http://blog.csdn.net/xiaoxian8023/article/details/24109185?utm_source=tuicool

阅读全文
0 0
原创粉丝点击