java getannotation_Java Annotation 总结

Annotation 被称为注解,在Java开发中是相当常见的,通过注解,我们可以简化代码提高开发效率。例如Override Annotation,这个应该算是在开发过程中使用最多的注解了。下面这个例子是Android Activity的onCreate方法最常用的注解:

@Overridepublic void onCreate(Bundle savedInstanceState);

1.Annotation 概念

An annotation is a form of metadata, that can be added to Java source code. Classes, methods, variables, parameters and packages may be annotated. Annotations have no direct effect on the operation of the code they annotate.

译文:

Annotation (注解) 表示的是能够添加到Java源代码的语法元数据。类、方法、变量、参数、包都可以被注解,可用来将信息元数据和程序元素进行关联。

2.Annotation 作用

a.标记作用,用于告诉编译器一些信息

b.编译时动态处理,如动态生成代码

c.运行时动态处理,如得到注解信息

这三个作用对应着后面自定义Annotation时说的@Retention三种值分别表示的Annotation

3.Annotation 分类

a.标准 Annotation

包括 Override, Deprecated, SuppressWarnings,标准 Annotation 是指 Java 自带的几个 Annotation,上面三个分别表示重写函数,不鼓励使用(有更好方式、使用有风险或已不在维护),忽略某项 Warning

b.元 Annotation

@Retention, @Target, @Inherited, @Documented,元 Annotation 是指用来定义 Annotation 的 Annotation。

—@Documented:是否会保存到 Javadoc 文档中

—@Retention:保留时间,可选值 SOURCE(源码时),CLASS(编译时),RUNTIME(运行时),默认为 CLASS,值为 SOURCE 大都为 Mark Annotation,这类 Annotation 大都用来校验,比如 Override, Deprecated, SuppressWarnings

—@Target:可以用来修饰哪些程序元素,如 TYPE, METHOD, CONSTRUCTOR, FIELD, PARAMETER 等,未标注则表示可修饰所有。

—@Inherited:是否可以被继承,默认为 false

c.自定义 Annotation

自定义 Annotation 表示自己根据需要定义的 Annotation,定义时需要用到上面的元 Annotation,这里只是一种分类而已,也可以根据作用域分为源码时、编译时、运行时 Annotation。

4.Annotation 自定义

a.定义

下面实现了一个自定义注解—MethodInfo:

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

@Inheritedpublic @interfaceMethodInfo {

String author()default "renhui";

String date();int version() default 1;

}

这里是 的实现部分

(1). 通过 @interface 定义,注解名即为自定义注解名

(2). 注解配置参数名为注解类的方法名,且:

a. 所有方法没有方法体,没有参数没有修饰符,实际只允许 public & abstract 修饰符,默认为 public ,不允许抛异常

b. 方法返回值只能是基本类型,String, Class, annotation, enumeration 或者是他们的一维数组

c. 若只有一个默认属性,可直接用 value() 函数。一个属性都没有表示该 Annotation 为 Mark Annotation

(3). 可以加 default 表示默认值

b.调用

public classApp {

@MethodInfo(

author= “renhui”,

date= "2016/01/14",

version= 1)publicString getAppName() {return "demo";

}

}

这里是调用自定义 Annotation——MethodInfo 的示例,MethodInfo Annotation 作用为给方法添加相关信息,包括 author、date、version

c.解析

运行时 Annotation 解析

(1) 运行时 Annotation 指 @Retention 为 RUNTIME 的 Annotation,可手动调用下面常用 API 解析

method.getAnnotation(AnnotationName.class);

method.getAnnotations();

method.isAnnotationPresent(AnnotationName.class);

其他 @Target 如 Field,Class 方法类似

getAnnotation(AnnotationName.class) 表示得到该 Target 某个 Annotation 的信息,因为一个 Target 可以被多个 Annotation 修饰

getAnnotations() 则表示得到该 Target 所有 Annotation

isAnnotationPresent(AnnotationName.class) 表示该 Target 是否被某个 Annotation 修饰

(2) 解析示例如下:

public static voidmain(String[] args) {try{

Class cls= Class.forName("*.App");for(Method method : cls.getMethods()) {

MethodInfo methodInfo=method.getAnnotation(

MethodInfo.class);if (methodInfo != null) {

System.out.println("method name:" +method.getName());

System.out.println("method author:" +methodInfo.author());

System.out.println("method version:" +methodInfo.version());

System.out.println("method date:" +methodInfo.date());

}

}

}catch(ClassNotFoundException e) {

e.printStackTrace();

}

}

以之前自定义的 MethodInfo 为例,利用 Target(这里是 Method)getAnnotation 函数得到 Annotation 信息,然后就可以调用 Annotation 的方法得到响应属性值

编译时 Annotation 解析

(1) 编译时 Annotation 指 @Retention 为 CLASS 的 Annotation,甴 apt(Annotation Processing Tool) 解析自动解析。需要做的

a. 自定义类集成自 AbstractProcessor

b. 重写其中的 process 函数

这块很多同学不理解,实际是 apt(Annotation Processing Tool) 在编译时自动查找所有继承自 AbstractProcessor 的类,然后调用他们的 process 方法去处理

(2) 假设之前自定义的 MethodInfo 的 @Retention 为 CLASS,解析示例如下:

@SupportedAnnotationTypes({ "*.MethodInfo"})public class MethodInfoProcessor extendsAbstractProcessor {

@Overridepublic boolean process(Set extends TypeElement>annotations, RoundEnvironment env) {

HashMap map = new HashMap();for(TypeElement te : annotations) {for(Element element : env.getElementsAnnotatedWith(te)) {

MethodInfo methodInfo= element.getAnnotation(MethodInfo.class);

map.put(element.getEnclosingElement().toString(), methodInfo.author());

}

}return false;

}

}

SupportedAnnotationTypes 表示这个 Processor 要处理的 Annotation 名字。

process 函数中参数 annotations 表示待处理的 Annotations,参数 env 表示当前或是之前的运行环境

process 函数返回值表示这组 annotations 是否被这个 Processor 接受,如果接受后续子的 rocessor 不会再对这个 Annotations 进行处理

使用编译时注解很实用的例子:做代码混淆时可以通过添加编译时注解并配合配置文件,达到指定的类、方法、对象等不进行混淆。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JAVA高级特性 1.静态导入:先举个离例子 。 import java.lang.Integer.parseInt; public class StaticImport { int x = parseInt("123"); System.out.println(x); } 这样的程序如果不在IDE 工具中输入,是很难看出这个程序代码会出现问题,可它偏偏就出问题了,这是为什么呢?因为程序里面有个静态方法,如果导入import static java.lang.Integer.parseInt;这样的程序就可以运行了。 2.可变参数与for循环增强 这个是一般的用法: public static void loop(String[] args){ for(int i=0;i<args.length;i++) { System.out.println(args[i]); } } 这个是JDK 增加的新特性的用法! public static void loop(int x,int... args ) { //这里的参数一定要以这样的形式输入 for(int i:args) { System.out.println(i); } } 3.枚举 写枚举技巧: 1. enum Gender{MALE,FEMALE,BOTH} 2. enum Gender{MALE,FEMALE,BOTH;public abstract getTitle();} 3.enum Gender{MALE{},FEMALE{},BOTH{};public abstract getTitle();} 4.填充各个{}中的getTitle方法。 下面是个红绿黄灯的例子: public enum TrafficLamp { RED(30){ public TrafficLamp next() { return GREEN; } }, GREEN(50){ public TrafficLamp next() { return YELLOW; } }, YELLOW(5){ public TrafficLamp next() { return RED; } }; public abstract TrafficLamp next(); private int time; private TrafficLamp(int time) { this.time = time; } 4.反射. 这个知识点,真是费了我好大劲才理解。当真正理解了,其实也就不难了。先举例子来理解什么是反射。 先建这样的一个类,带会下面有个类里面有反射成员变量的方法的! public class ReflectPoint { private int x; public int y; public ReflectPoint(int x, int y) { super(); this.x = x; this.y = y; } } public class Test{ String obj = (String)Class.forName("java.lang.String").newInstance(); 这是制造另一个章:Class.forName("java.lang.Integer") --------------------- 讲Constructor://构造方法 Constructor constructors[] = Class.forName("java.lang.String").getConstructors(); Constructor constructor = Class.forName("java.lang.String").getConstructor(StringBuffer.class); String str = (String)constructor.newInstance(new StringBuffer("abc")); System.out.println(str); class.newInstance()内部其实就是在用默认的构造方法 ----------------------- 讲Method //方法 Method charAt = Class.forName("java.lang.String").getMethod("charAt", int.class); System.out.println(charAt.invoke(str, 1)); ------------------------- 讲Field //成员变量 ReflectPoint point = new ReflectPoint(1,7); Field y = Class.forName("cn.itcast.corejava.ReflectPoint").getDeclaredField("y"); y.setAccessible(true); System.out.println(y.get(point)); Field x = Class.forName("cn.itcast.corejava.ReflectPoint").getDeclaredField("x"); x.setAccessible(true); System.out.println(x.get(point)); } 在这里我们运行的时候可以看出,ReflectPoint类里面的x和y 都可以打印出来了! 学习心得:先从这四个知识点来看,张老师的确很让人敬佩!以上的一些程序代码均为张老师课堂即兴发挥所写,也可以看出,张老师对JAVA特性的深刻理解能力!现在说说我对这些程序代码的理解,说实话,才开始听张老师讲的时候,我感觉很模糊的,但是当我真正理解了之后,觉得这些程序写的真是太好了。象以后我门在学习JAVA 的时候,一定要对每个知识点要慢慢的消化吃透,切不能走马观花。一个知识点必须要反复的动手练习,不然很难理解其中的奥秘所在的! 5.在JAVA的程序中,我经常性的看到字符前面有@这种标志的符号.这个就叫做注解! 下面是使用 @SuppressWarnings 来取消 deprecation 警告的一个例子: public class Test { @Deprecated //在eclipse下运行的时候,方法名上会加一横线 public static void sayHello() { } } public class Test2 { @SuppressWarnings("deprecation") //在mian方法内调用一个没有定义的方法时,运行的时候将会出现这一注解! public static void main(String [] args) { Test.sayHello(); } } @SuppressWarnings 批注允许您选择性地取消特定代码段(即,类或方法)中的警告。其中的想法是当您看到警告时,您将调查它,如果您确定它不是问题,您就可以添加一个 @SuppressWarnings 批注,以使您不会再看到警告。虽然它听起来似乎会屏蔽潜在的错误,但实际上它将提高代码安全性,因为它将防止您对警告无动于衷 — 您看到的每一个警告都将值得注意。 由如下代码引出@Override的讲解: User类中的方法: public boolean equals(User other) { return name.equals(other.name); } 下面的代码执行时将有问题: User user1 = new User(); User user2 = new User(); user1.setName("abc"); user2.setName("abc"); System.out.println(user1.equals(user2)); HashSet set = new HashSet(); set.add(user1); set.add(user2); System.out.println(set.size());//期望结果为1,但实际为2 这时候在User类的equals方法上加上@Override,发现了问题。 再看看这个代码:一看就知道有问题, 这里 就有个很好的解决办法,在写public @interface MyAnnotation {}这样的类的时候,下面的代码上的错误提示就是结束的! public class dsds { public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub System.out.println(User.class.isAnnotationPresent(MyAnnotation.class) ); System.out.println( User.class.getAnnotation(MyAnnotation.class) ); } } 运行的结果为:false null 下面演示了一下@Target和@Retention import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.TYPE}) //用于构造方法 @Retention(RetentionPolicy.RUNTIME) //在运行是加载Annotation到JVM中 public @interface MyAnnotation { public String value() default "yellow"; public int[] array() default {1,2}; public MetaAnnotation annotation() ; } 注解最主要的就是这么多,其实注解真正的,我们都很少留心的,但是有的注解会给你在写程序和查找错误的时,会有很大的帮助的! 6.泛型: 1、泛型的类型参数只能是类类型(包括自定义类),不能是简单类型。 2、同一种泛型可以对应多个版本(因为参数类型是不确定的),不同版本的泛型类实例是不兼容的。 3、泛型的类型参数可以有多个。 4、泛型的参数类型可以使用extends语句,例如<T extends superclass>。习惯上成为“有界类型”。 5、泛型的参数类型还可以是通配符类型。例如Class<?> classType = Class.forName(java.lang.String); 例子: a..使用?通配符可以引用其他各种参数化的类型,但不能调用与参数化有关的方法; Collection<?> c = new Vector<String>(); c.add("abc");//报错 c.size();//正确 所以,?通配符定义的变量主要用作引用,调用与参数化无关的方法,如果要调用与参数化相关的方法,那么必须在使用?通配符引用之前调用,否则就与java 5提供泛型的目的背道而驰了。 b..向下限定通配符: 正确:Vector<? extends Number> x = new Vector<Integer>(); 错误:Vector<? extends Number> x = new Vector<String>(); 向上限定通配符: 正确:Vector<? super Integer> x = new Vector<Number>(); 错误:Vector<? super Integer> x = new Vector<Byte>(); 7.代理 这里就直接先应用张老师写的代码然后再讲清其原理吧! package cn.itcast.corejava; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Collection; import java.util.Vector; public class ProxyTest { public static void main(String[] args) { System.out.println(Integer.class.getClassLoader()); //System.out.println(ProxyTest.class.getClassLoader().getParent().getClass().getName()); System.out.println(ProxyTest.class.getClassLoader().getClass().getName()); //test1(); //test2(); } private static void test3() { Vector v = new Vector(); class MyInvocationHandler implements InvocationHandler { Collection target = null; public Collection bind(Collection target) { this.target = target; Collection proxy1 = (Collection)Proxy.newProxyInstance( ProxyTest.class.getClassLoader(), new Class[]{Collection.class} , this); return proxy1; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub System.out.println("begin " + method.getName()); Object retval = method.invoke(target, args); System.out.println("end" + method.getName()); return retval; } } MyInvocationHandler handler = new MyInvocationHandler(); Collection proxy1 = handler.bind(v); System.out.println(proxy1.getClass().getName()); proxy1.add("abc"); proxy1.add("xyz"); System.out.println(proxy1.size()); } private static void test2() { Vector v = new Vector(); class MyInvocationHandler implements InvocationHandler { Collection target = null; public MyInvocationHandler(){} public MyInvocationHandler(Collection target){this.target = target;} public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub System.out.println("begin " + method.getName()); Object retval = method.invoke(target, args); System.out.println("end" + method.getName()); return retval; } } Collection proxy1 = (Collection)Proxy.newProxyInstance( ProxyTest.class.getClassLoader(), new Class[]{Collection.class} , new MyInvocationHandler(v)); System.out.println(proxy1.getClass().getName()); proxy1.add("abc"); proxy1.add("xyz"); System.out.println(proxy1.size()); } private static void test1() { Collection proxy = (Collection)Proxy.newProxyInstance( ProxyTest.class.getClassLoader(),//first parameter new Class[]{Collection.class} , //second parameter new InvocationHandler(){ //third parameter Vector target = new Vector(); public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub System.out.println("begin " + method.getName()); Object retval = method.invoke(target, args); System.out.println("end" + method.getName()); return retval; } } ); System.out.println(proxy.getClass().getName()); proxy.add("abc"); proxy.add("xyz"); System.out.println(proxy.size()); } } 以下是Proxy的API文档: public class Proxyextends extends Object implements Serializable Proxy provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods. To create a proxy for some interface Foo: InvocationHandler handler = new MyInvocationHandler(...); Class proxyClass = Proxy.getProxyClass( Foo.class.getClassLoader(), new Class[] { Foo.class }); Foo f = (Foo) proxyClass. getConstructor(new Class[] { InvocationHandler.class }). newInstance(new Object[] { handler }); or more simply: Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), new Class[] { Foo.class }, handler);从以上的程序中在方法中定义参数的时候总是三个参数,可这三个参数有分别代表什么意思呢!?现在以我自己个人的理解,比如我是买家,我要买本书,可是现在我有事,是不是需要别人代我买呢?那带我买的人是不是一定要到卖书的地方买呢?所以着中间产生了三个实体.说白了就是一种代理机制.需要三方一起运行! 代理其实很好理解的,而且会用固定的语法格式,很快会掌握这一原理的!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值