java 代理机制的实例详解

java 代理机制的实例详解

前言:

 java代理分静态代理和动态代理,动态代理有jdk代理和cglib代理两种,在运行时生成新的子类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;  
  } 
} 

Aspect注解

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代理机制的实例,如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

你可能感兴趣的:(java 代理机制的实例详解)