java中的注解
来源:互联网 发布:杭州java培训机构 编辑:程序博客网 时间:2024/06/11 21:30
注解在java中使用非常普遍,尤其是在spring中。在这里简单了解一下注解
首先新建一个注解类 NameTest.java
package com.qiao.Annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Retention(value=RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface NameTest {String value();}
注解上面的@Target 表示注解NameTest的作用范围,其中ElementType是一个枚举类型为
public enum ElementType { /** Class, interface (including annotation type), or enum declaration */ TYPE, /** Field declaration (includes enum constants) */ FIELD, /** Method declaration */ METHOD, /** Parameter declaration */ PARAMETER, /** Constructor declaration */ CONSTRUCTOR, /** Local variable declaration */ LOCAL_VARIABLE, /** Annotation type declaration */ ANNOTATION_TYPE, /** Package declaration */ PACKAGE}
ElementType.METHOD 表示该注解作用在方法上
@Retention表示注解的作用时机,其中RetentionPolicy也是一个枚举类型,为
public enum RetentionPolicy { /** * Annotations are to be discarded by the compiler. */ SOURCE, /** * Annotations are to be recorded in the class file by the compiler * but need not be retained by the VM at run time. This is the default * behavior. */ CLASS, /** * Annotations are to be recorded in the class file by the compiler and * retained by the VM at run time, so they may be read reflectively. * * @see java.lang.reflect.AnnotatedElement */ RUNTIME}RetentionPolicy.RUNTIME 表示jvm运行时,此注解可被读出
这两个注解是必须要有的。
注解的使用:
先写一个测试类
public class AnnotationTest {@NameTest(value = "java")public void test(){System.out.println(" bu niu bi ");}}
在写个Demo
import java.lang.annotation.Annotation;import java.lang.reflect.Method;import org.junit.Test;public class Demo {@SuppressWarnings("unchecked")@Testpublic void getAnnotation(){for(Method m : meth){ if(m.isAnnotationPresent(NameTest.class)){NameTest n = (NameTest) m.getAnnotation(NameTest.class);<span style="white-space:pre"></span>System.out.println(n.value()); }}}}
会输出NameTest的value --->“java”
0 0
- Java中的注解
- Java中的注解
- --java中的注解
- java中的注解
- java中的元注解
- java中的注解
- java中的注解
- Java中的注解
- eclipse中的java注解
- Java中的注解
- java中的注解
- java 中的注解
- Java中的注解
- java中的注解 详解
- java中的注解用法。
- Java中的注解(@ Annotation)
- Java中的注解
- java中的注解
- POJ3126 深搜
- 编程题#4:计算整数平方和(C++程序设计第10周)
- hdu 1097 A hard puzzle
- 20160130.CCPP体系详解(0009天)
- Java基础06 组合
- java中的注解
- 内核调试番外篇 - KDB的介绍与简单使用
- 数组
- 20160131.CCPP体系详解(0010天)
- c++类的成员变量使用普通变量还是指针
- Java基础07 包
- 20160201.CCPP体系详解(0011天)
- 内存学习
- 调试番外篇 - KGDB环境搭建与使用