0

I'm writing a library that uses Java Agents with Byte Buddy to perform runtime code generation. I need to create an expression to get the value from each field of a class.

How can I create an expression to access the field value? Currently I'm exploring the FieldDescriptionAPI but I not found anything to do this.

  • What kind of instrumentation are you using? What have you tried? – Rafael Winterhalter Feb 20 '19 at 07:51
  • I have another question. How can I get the `TypeDescription` for the class to be generated into a `MethodDelegation.to(AddFooMethod.class)`? – Wellington Costa Feb 20 '19 at 13:12
  • @RafaelWinterhalter I just need to create a method inside a class annotated with a specific annotation For example: `@MyAnnotation public class Person { private String name; private String email; // method to be generated public void generatedMethod() { System.out.println("name " + this.name + " email " + this.email); } }` Basically I want to generate a method inside a class that access all fields to get its value. – Wellington Costa Feb 21 '19 at 15:08

1 Answers1

0

From the additional information, you provided on GitHub, this is how you would approach this:

To create a StringBuilder you call MethodCall.construct(StringBuilder.class.getConstructor())

You can then call the append to the string builder like: MethodCall.invoke(StringBuilder.class.getMethod("append", Object.class)).onMethodCall(...).withField(...) where you start with the initial string builder and then reiterate for every field or constant supplying the last input to the next instance.

You would have to adjust the method based on the field type, if the type is primitive, for this to work. In the end, you have to do a final method call on toString.

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192