0

I am interested in auto generating some boiler plate methods (similar to Project Lombok). Byte Buddy friendly API seems promising but I'm not sure how to go about using it.

Here is a simple use-case. Lets say I have a class User.java

public class User {
    private String name;
}

I am planning on decorating this class with an annotation that would have an implementation of generating getter and setter for this. Using Byte Buddy, I tried the following:

public class MethodInterceptor {

    public static void main(String[] args) throws Exception {

        User user = new ByteBuddy()
                .subclass(User.class)            
                .defineMethod("getName", String.class, Visibility.PUBLIC)
                .intercept(FieldAccessor.ofBeanProperty())
                .defineMethod("setName", Void.TYPE, Visibility.PUBLIC)
                .withParameter(String.class)
                .intercept(FieldAccessor.ofBeanProperty())              
                .make()
                .load(User.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
                .getLoaded().newInstance();

        user.getClass().getDeclaredMethod("setName").invoke("Jaypal");
        Method m = user.getClass().getDeclaredMethod("getName");

        System.out.println((String) m.invoke(null));
    }
}

However, I am getting an exception

Exception in thread "main" java.lang.NoSuchMethodException: scratchpad.User$ByteBuddy$n0KYCYB5.setName()
    at java.lang.Class.getDeclaredMethod(Class.java:2130)
    at scratchpad.MethodInterceptor.main(MethodInterceptor.java:22)

Note: I know Project Lombok does support this, however this is just an experimentation. I am more interested in annotation drive code generation for another project. This is just a simple example I am trying out to see if Byte Buddy is suitable for such use case.

Any help or guidance would be much appreciated!

jaypal singh
  • 74,723
  • 23
  • 102
  • 147

1 Answers1

2

By declaring a method via

builder.defineMethod("setName", Void.TYPE, Visibility.PUBLIC)
       .withParameter(String.class)

you are declaring the method

public void setName(String s);

This method is available via

Method method = clazz.getDeclaredMethod("setName", String.class);

You forgot to add the parameter type.

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