I'm new to ByteBuddy and am trying to dive into understanding the library. It's a little tough, but I think I'm getting there. I'm trying to create a dynamic class that can intercept all getters and setters based on an interface and store the property names into a Set. I'm really struggling because I can't seem to get the method interceptor to work (probably just because of a lack of understanding). I've searched all over but unable to find enough information. Here's my example:
I have an interface that I want the dynamic class to implement defined as:
public interface SomePojo {
public String getName ();
public void setName (String name);
public String getFoo ();
public void setFoo (String foo);
}
I then defined a "SetterGetterInterceptor" as:
class SetterGetterInterceptor {
private Map<String,Object> container = new HashMap<String, Object> ();
public SetterGetterInterceptor () {
}
public Map<String, Object> getContainer () {
return this.container;
}
@RuntimeType
public Object intercept(@AllArguments Object[] allArguments,@Origin Method method) {
String methodName = method.getName ();
//
// We're only interested in getters and setters. If it's neither of these,
// we're just going to return null, but we should probably throw some
// exception like NoSuchMethod.
//
if (methodName.startsWith("get")) {
String property = methodName.substring (3);
return this.container.get(property);
} else if (methodName.startsWith("set")) {
String property = methodName.substring (3);
this.container.put(property, allArguments[0]);
}
return null;
}
}
And my main is defined as:
public class BBTest {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
SomePojo sp = new ByteBuddy ()
.subclass(SomePojo.class)
// .method(ElementMatchers.any()).intercept(new SetterGetterInterceptor ())
.make ()
.load(BBTest.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
.getLoaded()
.newInstance();
sp.setFoo("foo");
System.out.println (sp.getFoo());
}
}
I just cannot figure out how to get the dynamic class to intercept the getters and setters correctly. Any help would be appreciated, and thank you in advance. I commented out the .method() call because it was throwing an exception.