rascio
rascio

Reputation: 9279

Beanutils.copyProperties with protected set method

Is there a way to make BeanUtils works with a protected setXXX(X x) method? Or do you know some alternative to do this?

Something like:

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
}

Upvotes: 3

Views: 1283

Answers (2)

Kleber Ferreira
Kleber Ferreira

Reputation: 31

Try to use the 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
}

Upvotes: 3

kucing_terbang
kucing_terbang

Reputation: 5131

Well, too bad class MethodUtils that BeanUtils use to get the methods is check whether to only accept a public method. So, I don't think there is a straight forward way to make bean utils to get the protected method.

But, of course, you can use reflection to populate the fields like this.

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));
            }
        }
     }
}       

Upvotes: 1

Related Questions