0

I have the following example where I try to copy a private attribute from the source instance to the target instance.

public class MyClass {
  public void cloneTo(MyClass target) {
    target.identifier = this.identifier; // identifier is not null
    System.out.println(target.getIdentifier()) // problem: prints null
  }
}

This code usually should work, but the problem is that the MyClass instance is a CGLIB proxy: MyClass$EnhancerBySpringCGLIB$someId, and in this case, the identifier attribute is not set in the proxied target class, so when I call getIdentifier(), it returns null instead of the identifier.

Is it possible to copy private attributes without creating a getter/setter for each attribute?

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
Renato Dinhani
  • 35,057
  • 55
  • 139
  • 199

1 Answers1

2

This is not possible.

I take it from your question that you created a proxy MyClass$EnhancerBySpringCGLIB$someId that delegates its method invocations to another instance of MyClass?

Field operations in Java are not dispatched dynamically, i.e. there is no way to trigger an action when a field is set or read. This is only possible when a method is invoked. This means that there is no way to set the field of MyClass when MyClass$EnhancerBySpringCGLIB$someId is set.

Instead you need to:

  1. Define a setter for writing fields.
  2. Make MyClass$EnhancerBySpringCGLIB$someId not to be a delegator but an actual substitute for MyClass.
Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192