3

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
}
rascio
  • 8,968
  • 19
  • 68
  • 108

2 Answers2

3

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
}
Nick
  • 3,691
  • 18
  • 36
1

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));
            }
        }
     }
}       
kucing_terbang
  • 4,991
  • 2
  • 22
  • 28
  • Yes, but it is a little more complex than this, because `getDeclaredFields` gives you just the fields of the class but not those of its _supertype_. `BeanUtils` read the entire hierarchy and copy also those fields – rascio May 01 '15 at 18:07
  • Yes, you're right, if you want to get the fields of its __supertype__, then you need to `getSuperClass()` all the way until it hit class `Object`. – kucing_terbang May 01 '15 at 18:11