How do I create a setter on a field using byte buddy? What is the recommended syntax?
I managed to create the getter from a field (my original question here), but using the defineMethod
to create a setter is throwing a Method Implementation.Context.Default
... is no bean property
exception.
The suggested way to create a setter in this question seems to be outdated.
Here is my failing code using version 1.5.4 of byte-buddy:
public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, NoSuchMethodException {
Class<?> type = new ByteBuddy()
.subclass(Object.class)
.name("domain")
.defineField("id", int.class, Visibility.PRIVATE)
.defineMethod("getId", int.class, Visibility.PUBLIC).intercept(FieldAccessor.ofBeanProperty())
.defineMethod("setId", Void.TYPE, Visibility.PUBLIC).intercept(FieldAccessor.ofBeanProperty())
.make()
.load(sample.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
Object o = type.newInstance();
Field f = o.getClass().getDeclaredField("id");
f.setAccessible(true);
System.out.println(o.toString());
Method m = o.getClass().getDeclaredMethod("getId");
System.out.println(m.getName());
Method s = o.getClass().getDeclaredMethod("setId", int.class);
System.out.println(s.getName());
}