I am trying to generate efficient property accessors at runtime. Specifically this means I am generating classes that implement the following interface using ByteBuddy:
interface PropertyAccess<T> {
void set(Object instance, T value);
T get(Object instance);
}
Implementations should look something like this:
class SomeProperty implements PropertyAccess<String> {
public void set(Object o, String s) {
((SomeClass) o).setFoo(s);
}
public String get(Object o) {
return ((SomeClass) o).getFoo();
}
}
Doing this for a getter/setter pair is easy ( getter
and setter
being the java.lang.reflect.Method
objects for the actual getter and setter):
new ByteBuddy()
.subclass(Object.class)
.implement(PropertyAccess<String>.class) // pseudo syntax, I am using Guava's TypeToken here in reality
.method(named("get")).intercept(invoke(getter).onArgument(0))
.method(named("set")).intercept(invoke(setter).onArgument(0).withArgument(1))
(I left out here the assigner typing that will allow the cast from Object
to SomeClass
).
But now I want to also allow generating such a class for a directly accessed field and I cannot find a way to do so without writing a custom Implementation
class, because FieldAccessor
only allows access to fields of the generated class (or one of it's parents).
Am I missing something?
You are right, there is currently no way to access a field rather then a method. I think this should however be easy to fix by treating a field access similar to a getter or setter. I am tracking this limitation in ticket #225 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.