您的位置:首页 > 编程语言 > Java开发

Java注解入门

2016-01-15 23:32 609 查看
注解的分类

按运行机制分:

源码注解:只在源码中存在,编译后不存在
编译时注解:源码和编译后的class文件都存在(如@Override,@Deprecated,@SuppressWarnings)
运行时注解:能在程序运行时起作用(如spring的依赖注入)

按来源分:

来自JDK的注解
第三方的注解
自定义的注解

自定义注解

如下实例给出了自定义注解的基本方法

package com.flypie.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/*    @Target,@Retention,@Inherited,@Documented
*     这四个是对注解进行注解的元注解,负责自定义的注解的属性
*/
@Target({ElementType.TYPE,ElementType.METHOD})    //表示注解的作用对象,ElementType.TYPE表示类,ElementType.METHOD表示方法
@Retention(RetentionPolicy.RUNTIME)        //表示注解的保留机制,RetentionPolicy.RUNTIME表示运行时注解
@Inherited            //表示该注解可继承
@Documented            //表示该注解可生成文档
public @interface Design {
String author();        //注解成员,如果注解只有一个成员,则成员名必须为value(),成员类型只能为原始类型
int data() default 0;    //注解成员,默认值为0
}


使用注解

package com.flypie;

import com.flypie.annotations.Design;

@Design(author="flypie",data=100)    //使用自定义注解,有默认值的成员可以不用赋值,其余成员都要复值
public class Person {
@Design(author="flypie",data=90)
public void live(){

}
}


解析java注解

package com.flypie;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import com.flypie.annotations.Design;

public class Main {

public static void main(String[] args) throws ClassNotFoundException {

Class c=Class.forName("com.flypie.Person");        //使用类加载器加载类

//1、找到类上的注解
if(c.isAnnotationPresent(Design.class)){    //判断类是否被指定注解注解
Design d=(Design) c.getAnnotation(Design.class);    //拿到类上的指定注解实例
System.out.println(d.data());
}

//2、找到方法上的注解
Method[] ms=c.getMethods();
for(Method m:ms){
if(m.isAnnotationPresent(Design.class)){    //判断方法是否被指定注解注解
Design d=m.getAnnotation(Design.class);        //拿到类上的指定注解实例
System.out.println(d.data());
}
}

//3、另外一种方法
for(Method m:ms){
Annotation[] as=m.getAnnotations();        //拿到类上的注解集合
for(Annotation a:as){
if(a instanceof Design){        //判断指定注解
Design d=(Design) a;
System.out.println(d.data());
}
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: