java代理機構の実例と詳細

3462 ワード

java代理機構の実例と詳細
前言:
 javaエージェントは、静的エージェントと動的エージェントに分かれており、動的エージェントは、jdkエージェントとcglibエージェントの2種類があり、実行時には、新しいサブクラスのclassファイルを生成する。本文は主に動的エージェントを練習して、コードはメモ用です。代理の原理と仕組みについては、ネット上でよく書かれています。
jdkエージェント
インスタンスコード

import java.lang.reflect.InvocationHandler; 
import java.lang.reflect.Method; 
import java.lang.reflect.Proxy; 
 
public class ProxyFactory implements InvocationHandler {  
    
  private Object tarjectObject;  
  
  public Object creatProxyInstance(Object obj) {  
    this.tarjectObject = obj; 
    return Proxy.newProxyInstance(this.tarjectObject.getClass()  
        .getClassLoader(), this.tarjectObject.getClass()  
        .getInterfaces(), this);  
  }  
  
  @Override  
  public Object invoke(Object proxy, Method method, Object[] args)  
      throws Throwable {  
    Object result = null;  
    if (AssessUtils.isAssess()) {  
      result = method.invoke(this.tarjectObject, args);  
    }else{ 
      throw new NoAssessException("This server cannot run this service."); 
    } 
    return result;  
  } 
} 

cglibエージェント

import java.lang.reflect.Method; 
import org.springframework.cglib.proxy.Enhancer; 
import org.springframework.cglib.proxy.MethodInterceptor; 
import org.springframework.cglib.proxy.MethodProxy; 
 
public class ProxyCglibFactory implements MethodInterceptor {  
    
  private Object tarjectObject;  
  
  public Object creatProxyInstance(Object obj) {  
    this.tarjectObject = obj; 
    Enhancer enhancer=new Enhancer(); 
    enhancer.setSuperclass(this.tarjectObject.getClass()); 
    enhancer.setCallback(this); 
    return enhancer.create(); 
  } 
 
  @Override 
  public Object intercept(Object obj, Method method, Object[] args, 
      MethodProxy arg3) throws Throwable { 
    Object result = null;  
    if (AssessUtils.isAssess()) {  
      result = method.invoke(this.tarjectObject, args);  
    }else{ 
      throw new NoAssessException("This server cannot run this service."); 
    } 
    return result;  
  } 
} 

Asppectコメント

import org.aspectj.lang.JoinPoint; 
import org.aspectj.lang.ProceedingJoinPoint; 
import org.aspectj.lang.annotation.Around; 
import org.aspectj.lang.annotation.Aspect; 
import org.aspectj.lang.annotation.Before; 
import org.aspectj.lang.annotation.Pointcut; 
 
@Aspect 
public class AssessInterceptor { 
  @Pointcut(value="execution (* com..*.*(..))") 
  private void anyMethod(){}; 
   
  @Before("anyMethod()") 
  public void doBefore(JoinPoint joinPoint) throws NoAssessException{ 
    if (!AssessUtils.isAssess()) {  
      throw new NoAssessException("This server cannot run this service."); 
    } 
  } 
   
  /** 
   * Around        
   * @param pjp 
   * @throws Throwable 
   */ 
  @Around("anyMethod()") 
  public void invoke(ProceedingJoinPoint pjp) throws Throwable{ 
    pjp.proceed();  
  } 
 
} 
以上はjava代理機構の実例です。質問があれば、メッセージを残してください。あるいは、当サイトのコミュニティ交流討論をしてください。ありがとうございます。