Java注解

1、定义:

Java提供了一种源程序中的元素关联任何信息和任何元数据的途径和方法;

2、注解的分类

2.1 按照运行机制分
|- 源码注解 注解只在源码中存在,编译成*.class文件就不存在了;
|- 编译时注解 注解在源码和*.class文件中都存在;像@Override、@Deprecated、@Suppvisewarnings;
|- 运行时注解 在运行阶段还起作用,甚至会影响运行逻辑的注解;像@Autowired;
2.2 按照来源分
|- 来自JDK
|- 来自第三方
|- 自定义注解

2.3 元注解 - 注解的注解

3、自定义注解:

示例:

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({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description {
	String desc();
	String author();
	int age() default 18;
}

3.1 自定义注解的语法要求:
使用@interface关键字定义注解;
成员以无参数无异常的方式声明;
可以用default为成员指定默认值;
成员类型是受限的,合法的类型包括基本数据类型及String、Class、Annotation、Enumeration;
如果注解只有一个成员,则成员名必须取名为value(),在使用时可以忽略成员名和赋值等号;

注解可以没有成员,没有成员的注解成为标识注解;

元注解:
Target - 注解的作用域
CONSTRUCTOR 构造方法声明
FIELD 字段声明
LOCAL_VARIABLE 局部变量声明
METHOD 方法声明
PACKAGE 包声明
PARAMETER 参数声明
TYPE 类,接口
@Retention - 生命周期
SOURCE 只在源码显示,编译时丢弃
CLASS 编译时会记录到class中,运行时忽略
RUNTIME 运行时存在,可以通过反射读取
@Inherited - 标识注解,允许子注解继承
@Documented - 生成javadoc时会包含注解

3.2 使用自定义注解

示例:

@Description(desc = "I am eyeColor", author = "hellboy", age = 18)
public String eyeColor() {
	return "red";
}

语法:
@<注解名>(<成员名1>=<成员值1>, <成员名2>=<成员值2>, ...)

 

4、解析注解

通过反射获取类、函数或成员上的运行时注解信息,从而实现动态控制程序运行的逻辑;

两种解析方式:

public static void main(String[] args) {
	try {
		Class c = Class.forName("com.yiniu.study.controller.TestDemo");

		boolean isExist = c.isAnnotationPresent(Description.class);
		if (isExist) {
			Description d = (Description) c.getAnnotation(Description.class);
			System.out.println(d.value());
		}
		Method[] methods = c.getMethods();
		for (Method method : methods) {
			boolean isMethodExist = method.isAnnotationPresent(Description.class);
			if (isMethodExist) {
				Description de = method.getAnnotation(Description.class);
				System.out.println(de.value());
			}
		}

		Annotation[] classAnnotations = c.getAnnotations();
		for (Annotation annotation : classAnnotations) {
			if (annotation instanceof Description) {
				Description d = (Description) annotation;
				System.out.println(d.value());
			}
		}
		for (Method method : methods) {
			Annotation[] annotations = method.getAnnotations();
			for (Annotation annotation : annotations) {
				if (annotation instanceof Description) {
					Description d = (Description) annotation;
					System.out.println(d.value());
				}
			}
		}
	} catch (ClassNotFoundException e) {
		e.printStackTrace();
	}
}

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值