BitBuddy를 사용하여 프록시 빈을 동적으로 생성하려고 시도 할 수 있습니다. https://bytebuddy.net/
아래 샘플은 메소드의 특성 필드를 프록시하는 방법을 보여줍니다. 이것은 샘플 일 뿐이며, 아마도 랩을 사용하여 리플렉션을 사용하여 동적을 추가해야 할 수도 있지만 코드를 동적으로 확장하려는 경우 상당히 흥미로운 옵션이라고 생각합니다.
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import net.bytebuddy.jar.asm.Opcodes;
import org.apache.commons.beanutils.BeanUtils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class M1 {
public static class PojoBase {
int property;
String strProp;
}
public static class Intereptor {
private final String fieldName;
private final PojoBase pojo;
public Intereptor(PojoBase pojo, String fieldName) {
this.pojo = pojo;
this.fieldName = fieldName;
}
@RuntimeType
public Object intercept(@RuntimeType Object value) throws NoSuchFieldException, IllegalAccessException {
Field field = pojo.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
field.set(pojo, value);
return value;
}
}
public static void main(String... args) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
PojoBase origBean = new PojoBase();
PojoBase destBean = new PojoBase();
origBean.property = 555666;
origBean.strProp = "FooBar";
DynamicType.Builder<Object> stub = new ByteBuddy()
.subclass(Object.class);
DynamicType.Builder.MethodDefinition.ReceiverTypeDefinition<Object> dynamic = stub.defineMethod("getProperty", Integer.TYPE, Opcodes.ACC_PUBLIC).intercept(FixedValue.value(origBean.property))
.defineMethod("setProperty", Void.TYPE, Opcodes.ACC_PUBLIC).withParameters(Integer.TYPE).intercept(MethodDelegation.to(new Intereptor(destBean, "property")))
.defineMethod("getStrProp", String.class, Opcodes.ACC_PUBLIC).intercept(FixedValue.value(origBean.strProp))
.defineMethod("setStrProp", Void.TYPE, Opcodes.ACC_PUBLIC).withParameters(String.class).intercept(MethodDelegation.to(new Intereptor(destBean, "strProp")));
Class<?> dynamicType = dynamic.make()
.load(M1.class.getClassLoader())
.getLoaded();
Object readerObject = dynamicType.newInstance();
Object writterObject = dynamicType.newInstance();
BeanUtils.copyProperties(readerObject, writterObject);
System.out.println("Out property:" + destBean.property);
System.out.println("Out strProp:" + destBean.property);
}
}