I'm trying to get ByteBuddy to implement a step builder, given an interface for that builder. I'm stuck on 2 places.
- How to create a setter that returns the current instance for method chaining?
I started with:
.method(ElementMatchers.isSetter())
.intercept(FieldAccessor.ofBeanProperty());
only I'd like to return the current builder instance so we can chain calls like:
final Object obj = ...builder().id(100).name("test").build();
so instead I created an interceptor like this, which seems like a hack and I'd like to avoid reflection where possible:
@RuntimeType
public Object intercept(@RuntimeType Object arg, @This Object source, @Origin Method method)
{
try
{
// Field name is same as method name.
final Field field = source.getClass().getDeclaredField(method.getName());
field.setAccessible(true);
field.set(source, arg);
}
catch (Throwable ex)
{
throw new Error(ex);
}
// Return current builder instance.
return source;
}
- Is there an easy way to access defined fields on a class I'm defining without reflection?
Currently I add fields to the builder class in a loop and my build method on the builder is intercepted like this:
private static final class InterBuilder
{
private final Collection<String> fields;
private final Constructor<?> constructor;
InterBuilder(final Constructor<?> constructor, final Collection<String> fields)
{
this.constructor = constructor;
this.fields = fields;
}
@RuntimeType
public Object intercept(@This Object source, @Origin Method method)
{
try
{
final Object[] args = Arrays.stream(source.getClass().getDeclaredFields())
.filter(f -> this.fields.contains(f.getName()))
.map(f -> { try {
f.setAccessible(true);
return f.get(source); }
catch (Throwable ex) { throw new Error(ex); } })
.toArray();
// Invoke a constructor passing in the private field values from the builder...
return this.constructor.newInstance(args);
}
catch (Throwable ex)
{
throw new Error(ex);
}
}
}
I saw the @FieldValue annoation. I don't suppose there is something that will give me all fields without knowing their names up front?
The code is a proof of concept at this point. Are there better ways to do what I'm doing here?
Thank you!