자바 동적 에이전트 의 실현
1. 행위 규범 을 정의 합 니 다.
public interface IService {
public String doSomething();
}
이상 의 인 터 페 이 스 는 목표 대상 에 의 해 이 루어 지면 됩 니 다. 왜냐하면 우 리 는 지금 스스로 대 리 를 만 들 필요 가 없 기 때문에 JDK 동적 으로 대 리 를 만 듭 니 다.2. 자신의 Invocation Handler 실현
public class MyInvocationHandler implements InvocationHandler {
//
private Object target;
public MyInvocationHandler(Object target) {
super();
this.target = target;
}
/**
* InvocationHandler
*
*/
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println(" ...");
//
Object result = method.invoke(target, args);
System.out.println(" ...");
return result;
}
/**
*
*
* @return
*/
public Object getProxy() {
return Proxy.newProxyInstance(Thread.currentThread()
.getContextClassLoader(), target.getClass().getInterfaces(),
this);
}
}
이상 은 자신의 Invocation Handler 를 실현 한 것 입 니 다. 이것 은 기본적으로 규범 화 된 쓰기 입 니 다. 그 다음 에 우리 가 자신의 Invocation Handler 를 만들어 야 한다 면 모두 이 형식 에 따라 합 니 다.getProxy () 방법 에서 Proxy 류 를 사 용 했 습 니 다. 이 종 류 는 JDK 다음 시스템 클래스 입 니 다. 제 가 이전 글 에서 자신의 Proxy 류 가 아 닙 니 다.3. 목표 달성 대상
public class RealService implements IService {
public String doSomething() {
System.out.println(" ...");
return " ...";
}
}
4. 대상 의 사용 및 인쇄 테스트
public static void main(String[] args) {
//
IService userService = new RealService();
// InvocationHandler
MyInvocationHandler invocationHandler = new MyInvocationHandler(
userService);
//
IService proxy = (IService) invocationHandler.getProxy();
//
proxy.doSomething();
}
//==================
...
...
...
관련 자료
(1) 동적 에이전트 의 장점 과 응용 장면: 이동 하 십시오.http://www.zhihu.com/question/20794107;
(2) 자바 동적 에이전트 에 대한 상세 한 구현: 다음으로 이동 하 십시오.http://rejoy.iteye.com/blog/1627405;
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Java 동적 에이전트 및 CGLIB 상세 설명2. 동적 에이전트 클래스는 정적 에이전트보다 에이전트 클래스가 원 인터페이스를 실현하지 않고 InvocationHandler를 실현하는 것을 알 수 있습니다.통과 동적으로 프록시 클래스를 생성합니다. 이렇게 하면 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.