【问题标题】:Beanutils.copyProperties with protected set methodBeanutils.copyProperties 和受保护的 set 方法
【发布时间】:2015-05-01 15:51:38
【问题描述】:

有没有办法让 BeanUtils 与 protected setXXX(X x) 方法一起工作?或者您知道其他方法吗?

类似:

public class A{
    private String text;

    public String getText(){
         return this.text;
    }
    protected void setText(String text){
         this.text = text;
    }
}
public class B{
    private String text;

    public String getText(){
         return this.text;
    }
    protected void setText(String text){
         this.text = text;
    }
}

public static void main(String[] args){
     A a = new A();
     a.setText("A text");
     B b = new B();
     BeanUtils.copyProperties(b, a);
     System.out.println(b.getText()); //A text
}

【问题讨论】:

    标签: java copy javabeans apache-commons-beanutils


    【解决方案1】:

    尝试使用BULL (Bean Utils Light Library)

    public static void main(String[] args) {
       A a = new A();
       a.setText("A text");
       B b = BeanUtils.getTransformer(B.class).apply(a);     
       System.out.println(b.getText()); //A text
    }
    

    【讨论】:

    • 有趣的是,这个的创建者是我的同事 :) 很高兴看到它被建议
    【解决方案2】:

    好吧,太糟糕的类MethodUtils BeanUtils 用来获取方法是检查是否只接受公共方法。所以,我认为没有一种直接的方法可以让 bean utils 获得受保护的方法。

    但是,当然,您可以使用反射来填充这样的字段。

    for (Field field : a.getClass().getDeclaredFields()) {
        for (Method method : b.getClass().getDeclaredMethods()) {
            method.setAccessible(true);
            String fieldName = Character.toUpperCase(field.getName().charAt(0)) + field.getName().substring(1);
            if (method.getName().equals("set" + fieldName)) {
                method.invoke(b, a.getClass().getMethod("get" + fieldName).invoke(a));
                }
            }
         }
    }       
    

    【讨论】:

    • 是的,但它比这更复杂一些,因为getDeclaredFields 只为您提供类的字段,而不是其超类型 的字段。 BeanUtils 读取整个层次结构并复制这些字段
    • 是的,你是对的,如果你想得到它的超类型的字段,那么你需要一直getSuperClass(),直到它到达类Object .
    猜你喜欢
    • 2020-03-31
    • 2011-07-09
    • 2011-02-03
    • 2016-02-19
    • 2015-08-09
    • 1970-01-01
    • 2011-10-26
    • 2012-01-09
    • 2013-01-18
    相关资源
    最近更新 更多