美文网首页
anno_proxy

anno_proxy

作者: 呦後 | 来源:发表于2017-06-12 20:03 被阅读0次

[TOC]

注解

自定义注解

开发步骤

1.创建一个@interface
2.String value();抽象方法用以接收数据
3.使用元注解,描述自定义注解

4.@Target指定注解可以加在哪里

-ElementType.TYPE:可在类和接口上面
-ElementType.METHOD:可方法上
-ElementType.FIELD:可在属性

5.@Retention指定注解在什么时候有用

  • RetentionPolicy.RUNTIME:注解保留到运行时
  • RetentionPolicy.ClASS:注解保留到Class文件中
  • RetentionPolicy.SOURCE:注解保留到java编译时期

6.@Inherited可以被继承

jdk动态代理

1.被代理类必须实现一个接口,任意接口

public class Bus implements Runnable{}

2.创建一个类实现InvocationHandler,该类用来对象代理对象进行方法的增强

public class TimeInvocation implements InvocationHandler{
    private Object target;//被代理对象
    public TimeInvocation(Object target){
        this.target=target;
    }
}

3.在invoke()方法中调用被代理对象的方法,并且添加增强的代码

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        long time1=System.currentTimeMillis();
        //调用被代理对象的方法
        method.invoke(target, args);
        long time2=System.currentTimeMillis();
        System.out.println(time2-time1);
        return null;
    }

4.通过Proxy.newProxyInstance(ClasLoader, Class, InvovationHandler)创建代理类对象

5.调用代理对象的方法

   TimeInvocation time=new TimeInvocation(s);
   Class<?> clazz=s.getClass();
   Runnable s1= (Runnable)Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), time);
   s1.run();

<a href="http://naotu.baidu.com/file/c75d0eab19eb600147a88885cfe1c938?token=e54d3196199a75cd">注释的脑图</a>

相关文章

  • anno_proxy

    [TOC] 自定义注解 开发步骤 1.创建一个@interface2.String value();抽象方法用以接...

  • anno_proxy

    自定义注解 定义:注解(Annotation),也叫元数据。一种代码级别的说明。它是JDK1.5及以后版本引入的一...

网友评论

      本文标题:anno_proxy

      本文链接:https://www.haomeiwen.com/subject/wgfrqxtx.html