欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 代理机制的实例详解

程序员文章站 2024-02-25 09:15:40
java 代理机制的实例详解 前言:  java代理分静态代理和动态代理,动态代理有jdk代理和cglib代理两种,在运行时生成新的子类class文件。本文主...

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