博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java中的注解
阅读量:4319 次
发布时间:2019-06-06

本文共 2113 字,大约阅读时间需要 7 分钟。

注解在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")	@Test	public void getAnnotation(){				for(Method m : meth){		    if(m.isAnnotationPresent(NameTest.class)){			NameTest n = (NameTest) m.getAnnotation(NameTest.class);			System.out.println(n.value());		    }		}	}}
会输出NameTest的value  --->“java”

转载于:https://www.cnblogs.com/Iqiaoxun/p/5350587.html

你可能感兴趣的文章
NoSQL 简介及什么是AICD
查看>>
hibernate+mysql的连接池配置
查看>>
条件运算符 (?:)
查看>>
javascript Array(数组)
查看>>
HDU1518 Square 【剪枝】
查看>>
桥接模式
查看>>
crm查询记录共享给了哪些人
查看>>
android windows 上JNI编程
查看>>
现代信息环境中的云计算
查看>>
PHP中可变变量到底有什么用?
查看>>
谈一谈最近关闭的Kindle人论坛
查看>>
mysql 常用命令行
查看>>
PDF.NET数据开发框架 之SQL-MAP使用存储过程
查看>>
如何用eclipse运行导入的maven项目
查看>>
svn服务器安装
查看>>
arya使用流程
查看>>
最近要做的事
查看>>
maven 常用命令
查看>>
Hive-ORC文件存储格式(续)
查看>>
init()和onEnter()方法的区别
查看>>