java注解

来源:互联网 发布:有什么好用的水乳 知乎 编辑:程序博客网 时间:2024/06/05 17:21

1.定义:注解是代码里做的特殊标记,这些标记可以在编译、类记载、类运行、时在不改变原有的逻辑情况下 被读取,并执行相应的处理,通过使用注解,程序员可以在源文件中嵌入一些补充信息 代码分析工具、开发工具和部署工具可以通过这些补充信息进行验证或者进行部署  注解类似于修饰符一样被使用,可以用于包、类、构造方法、方法、成员变量、参数、局部变量的声明。

2.自定义一个注解:

<pre name="code" class="java">package com.tudou.Annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;/** * 自定义一个注解 * @author hugang * */import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;//value值代表的是自己的注解什么时期产生作用@Retention(value = RetentionPolicy.RUNTIME)//可以生成文档@Documented/** * Target注解:用来限制注解的使用范围 * 1.TYPE: 正能在类的接口或者枚举上使用 * 2.FILED:在成员变量中使用 * 3.METHOD:在方法中使用 * 4.PARAMETER:在参数上使用 * 5.CONSTRUCTOR:在构造中使用 * 6.LOCAL_VARIABLE:局部变量上使用 * 7.ANNOTATION_TYPE:只能在Annotation上使用 * 8.PACKAGE:只能在包中使用 * @author hugang * */@Target({ElementType.TYPE,ElementType.METHOD,ElementType.PARAMETER})
//表示定义的注解允许被继承下来,不写则不允许被继承@Inheritedpublic @interface MyAnnotation {public String name();public String Info();//注解中定义属性public String ss()default "SS";//属性赋予默认值public String[] names();public String[] names2()default {"dd"};//定义枚举变量public MyEnum sex();}

定义一个枚举,用来表示性别

package com.tudou.Annotation;public enum MyEnum {BOY,GIRL}


使用注解

package com.tudou.Annotation;@MyAnnotation(Info = "TD",name = "LB",names = {"土豆","萝卜"},sex = MyEnum.BOY)//使用自定义的注解,记得给属性赋值public class Person {private String name;@Overridepublic String toString() {return super.toString();}@Deprecated//表示方法已经过时public void print(){System.out.println("name:"+name);}public String getName() {return name;}public void setName(String name) {this.name = name;}//在参数上使用注解public void printf(@MyAnnotation(Info = "TD",name = "LB",names = {"土豆","萝卜"},sex = MyEnum.BOY)String n){System.out.println(n);}}
测试
package com.tudou.Annotation;import java.lang.annotation.Annotation;public class AnnoCationDemo {public static void main(String[] args) throws ClassNotFoundException {//使用反射解析注解Class<?> c = Class.forName("com.tudou.Annotation.Person");//获取当前类标记的所有注解Annotation[] a = c.getAnnotations();for (Annotation annotation : a) {//判断注解是不是指定注解if(c.isAnnotationPresent(MyAnnotation.class)){MyAnnotation myAnnotation = (MyAnnotation)annotation;System.out.println(myAnnotation.toString());}}}}
打印结果为




0 0