2011-12-05 3 views
1

개체를 생성하고 모든 공용 메서드를 가로채는 팩터 리 클래스를 구현하려고합니다.Java - 호출 처리기를 만드시겠습니까?

여기서 두 가지 메소드를 호출하려고합니다. 1 : 이미 호출 된 메소드 2 : 내 기반의 메소드. 어떻게하면이 아이디어를 얻을 수 있을까요?

public class LoggerFactory { 


    public LoggerFactory() { 
    } 

     // Clazz is always a class inheriting from Loggable 
    public Object newInstance(Class clazz) { 
     return Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] {clazz}, handler); 
    } 

    private InvocationHandler handler = new InvocationHandler() { 

     @Override 
     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 
      // Call logStartingTime on object 

      // Call invoked method on object 

      // Call logEndingTime on object 

      return null; 
     } 
    }; 
} 

내 추상 클래스 :

public abstract class Loggable { 

     void logStartingTime() { 
      log.info(“start time = ” + new Date()); 
      // also log some info about the state of the object 
     } 

     void logEndingTime() { 
      log.info(“ending time = ” + new Date()); 
      // also log some info about the state of the object 
     } 
} 

답변

3

AspectJ으로 달성 할 수 있다고 생각합니다.

+0

+1. 좀 더 구체적으로 말하자면'Loggable'을 기본 클래스로 가지는 것은별로 의미가 없습니다. 포함시키고 자하는 다른 구성 가능한 행동을했다면 어떨까요? AOP는 더 나은 접근 방법처럼 보입니다. – Dan

2

Proxy 클래스는 프록시 인터페이스가 아닌 클래스를 지원합니다.

CGLib에는 클래스에서 프록시를 만들고 필요한 것을 수행 할 수있는 기능이 있습니다. Beans example은 좋은 시작점을 제공 할 수 있습니다.

관련 문제