4

It's my first experience with ByteBuddy and I'd like to dynamically create a subclass of java.lang.Object with only one public field named myValue of type java.lang.String and a default value of "Hello World !". Unfortunately, after calling the myClass.newInstance() the field's value is null (within the Eclipse debugger).

final Class<?> myClass = new ByteBuddy().subclass(Object.class).name("test.MyClass")
    .defineField("myValue", String.class, Visibility.PUBLIC)
    .value("Hello World !")
    .make()
    .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.INJECTION).getLoaded();
Object myObject = myClass.newInstance();

Am I missing something here ?

I'm using Eclipse Mars.2, an Oracle JDK 1.7.0_75 and ByteBuddy-1.2.3

Thomas Naskali
  • 551
  • 5
  • 19
  • I'm confused why you want to do this? – OneCricketeer Mar 01 '16 at 13:51
  • The reason is not really relevant as I'm just exploring the library (as the "Hello World !" value suggests). The class I'd like to emulate would look like this : `package test; public class MyClass { public int myValue = "Hello World !"; }` – Thomas Naskali Mar 01 '16 at 13:55

1 Answers1

3

The value method is writing a constant pool default value for a field what is only possible in Java for static fields. Byte Buddy should throw an exception in this scenario and not suppress the error silently. I will change this behavior for the next version and update the javadoc to be more clear about what the value method is doing.

If you want to set a field value, you need to intercept any constructor to set the field value. You can do this in different ways such as using a MethodDelegation in combination with a @FieldProxy annotation. The documentation shows examples of how this can be done.

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
  • I was suspecting the `value` method's purpose was not to set the corresponding field's value. I agree that the javadoc could be more explicit. Thank you for your feedback and keep up the good work ! – Thomas Naskali Mar 02 '16 at 09:28