Java注解和代理实现
Posted 感遇
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java注解和代理实现相关的知识,希望对你有一定的参考价值。
1、定义注解
import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MethodAnnotation { String name() default "Default Annotation Name"; String url() default "default.com"; }
2、使用注解的信息类
public interface IProxyTest { @MethodAnnotation() public void testMethodAnnotation(); @MethodAnnotation(name="亚马逊",url="z.cn") public void testMethodAnnotationWithValue(); }
3、实现该接口
public class ProxyTestImpl implements IProxyTest { public void testMethodAnnotation() { System.out.println("UseAnnotion->testMethodAnnotation"); } public void testMethodAnnotationWithValue() { System.out.println("UseAnnotion->testMethodAnnotationWithValue"); } }
4、动态代理类实现及main测试
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class LogProxy implements InvocationHandler { private static int count = 0; private Object target; private LogProxy() { } private static Object getInstance(Object o) { LogProxy lp = new LogProxy(); lp.target = o; Object result = Proxy.newProxyInstance(o.getClass().getClassLoader(), o .getClass().getInterfaces(), lp);//代理对象 return result; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.isAnnotationPresent(MethodAnnotation.class)) { MethodAnnotation annotation = method .getAnnotation(MethodAnnotation.class); count++;//使用场景:统计接口的使用次数,可以在性能范围内降级 System.out.println("执行方法" + method.getName() + ":" + count); } Object obj = method.invoke(target, args); return obj; } public static void main(String[] args) { IProxyTest ua = new ProxyTestImpl(); IProxyTest lp = (IProxyTest) LogProxy.getInstance(ua); lp.testMethodAnnotation(); lp.testMethodAnnotationWithValue(); } }
以上是关于Java注解和代理实现的主要内容,如果未能解决你的问题,请参考以下文章