2016-10-31 7 views
0

나는 몇 가지 클래스의 프록시 객체를 생성하기 위해 CGLIB를 사용하고, 물론cglib를 사용하여 사용자 정의 필드로 프록시를 생성하는 방법은 무엇입니까?

String customFieldName = "myCustomField"; 
    Enhancer enhancer = new Enhancer(); 
    enhancer.setSuperclass(targetClass); 
    // What can I do to add custom field to the proxy class ? 

    enhancer.setCallback(new MethodInterceptor() { 
     @Override 
     public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { 
      // I'd access the custom field value here 
      Field field = obj.getClass().getField(customFieldName); 
      Object customFieldValue = field.get(obj); 

      // do something 

      return proxy.invokeSuper(obj, args); 
     } 
    }); 

아래 그림처럼 나는 대안에 값을 바인딩지도를 사용하고있는 프록시 객체에 대한 일부 손님 필드를 바인드해야 원본 개체가 있지만 나는 이것을 정말로하고 싶지 않습니다.

아무도 아이디어가 있습니까?

답변

0

cglib를 사용할 때 불가능합니다. 기본 ASM API에 액세스하여 바이트 코드로 필드를 직접 추가하지 않는 한 API가 없습니다. 당신이 도구를 변경하고자하는 경우, 당신은 그러나 Byte Buddy을 사용할 수 있습니다, 도서관 나는 유지한다 :

Class<? extends TargetClass> proxy = new ByteBuddy() 
    .subclass(targetClass) 
    .method(any()) 
    .intercept(MethodDelegation.to(MyInterceptor.class) 
          .andThen(SuperMethodCall.INSTANCE) 
    .defineField("myCustomField", Object.class, Visibility.PUBLIC) 
    .make() 
    .load(targetClass.getClassLoader()) 
    .getLoaded(); 

class MyInterceptor { 
    static void intercept(@FieldValue("myCustomField") Object myCustomField) { 
    // do something 
    } 
} 

CGLIB과 함께, 당신은 다른 방법 콜백을 사용하여 각 개별 프록시 특정 증강 인스턴스에 위임 할 콜백을 추가 할 수 있습니다 수업.