【问题标题】:Usage of ReflectionUtils and BeanUtils for private fields私有字段使用 ReflectionUtils 和 BeanUtils
【发布时间】:2014-02-24 03:39:28
【问题描述】:

我需要使用另一个对象的字段在一个对象中设置一些私有字段。这两个对象可能不是同一类的实例。
我从简短的阅读中看到,我可以为此使用 Apache 的 BeanUtils 和 Spring 的 ReflectionUtils。我找不到关于安全性、性能、支持等方面的令人满意的解释。
该解决方案也将用于生产环境,因此我需要一个具体的解决方案。 对于此类任务,您建议采用哪种方法。

【问题讨论】:

    标签: reflection private apache-commons-beanutils


    【解决方案1】:

    我认为您只需要使用 BeanUtils 库。查看我的示例,我将属性从 CustomerBean 复制到 SellerBean。

    package testes.beanutils;
    
    import org.apache.commons.beanutils.BeanUtils;
    
    public class Main {
    
    public static void main(String[] args) throws Exception {
        Customer customer = new Customer();
        customer.setId((long)1);
        customer.setName("Bruno");
        customer.setLastname("Tafarelo");
    
        Seller seller = new Seller();
    
        BeanUtils.copyProperties(seller, customer);
    
        System.out.println(customer);
        System.out.println(seller);
        }
    }
    
    class Customer {
    
    private Long id;
    
    private String name;
    
    private String lastname;
    
    //getters and setters
    
    //toString
    }
    
    class Seller {
    
    private Long id;
    
    private String name;
    
    private int sales;
    
    //getters and setters
    
    //toString
    }
    

    【讨论】:

    • 谢谢,但为什么呢?我正在寻找一个答案来解释为什么我应该使用一个而不是另一个。他们似乎都有能力做你的榜样。
    • 好吧。我无法解释 spring 反射,但如果 springcore 已经是我的应用程序的依赖项,我只会做这个 api。 BeanUtils 小巧、简单,在很多项目中都使用过,例如 struts。 BeanUtils,可以做缓存来加速反射的使用。安全性,我知道谁不能隐式地设置不同类型的值的属性。我使用 BeanUtils 将表单 html(请求参数)解析为 bean,我只是无法填充复杂的 Collection,但简单的列表和嵌套属性效果很好。抱歉,我不能多说或比较这个库。
    猜你喜欢
    • 2011-09-01
    • 2013-05-07
    • 2011-08-13
    • 1970-01-01
    • 2010-09-29
    • 2011-08-05
    • 2015-08-12
    • 1970-01-01
    相关资源
    最近更新 更多