注解

注解/Annotation也是一种引用数据类型,编译后生成字节码文件。

语法格式:

{修饰符} @interface 注解名{

}

使用时的语法:@注解名

注解可以出现在方法上、类上、变量上、注解上,几乎所有位置上。

(一)Override注解:

JDK内置的,必须出现在重写父类方法的地方,是给编译器参考的,和运行没有关系。

凡是带有这个注解的,编译器都会检查是不是重写的方法,不是就报错。

(二)元注解

指修饰注解的注解。常见元注解@Target(注明注解可以出现在哪里)@Retention(注明注解可以保存在哪里)

@Target(ElementType.Method)表示注解只能出现在方法上,ElementType是枚举类型

@Retention(RetentionPolicy.SOURCE)表明注解只能保存在java源文件中

如果是.CLASS表明只能保存在字节码中,如果是.RUNTIME表明保存在字节码中并且可以被反射读取。

(三)Deprecated注解

@Depracated表明这个元素已经过时,后面调用这个方法编译的时候就会有减号在上面

(四)注解中的属性

注解中有属性的,必须给属性赋值

如;@Annotation(name="String"),name是定义Annotation时写的一个属性

注解中的属性可以是除引用数据类型以外的(继承Object的都不行),包括其数组

如果有数组的话,调用赋值使用大括号。

public @interface Annotation{

String name();

int age() defalut 24;//默认年龄24,不用调用的时候赋值了。

String value();//如果名字叫value赋值时可以不写,如@Annotation("value"),但前提是只有value这么一个属性

Season[] s();//Season是枚举类型
}

(四)反射注解

public static void main(String[] args) throws  Exception{
		Class classUser=Class.forName("test.Account");
		//判断类上是否有这个注解,如果有获得这个注解对象
		if (classUser.isAnnotationPresent(MyAnnotation.class)) {
			MyAnnotation o=(MyAnnotation) classUser.getAnnotation(MyAnnotation.class);
			System.out.println("获取注解"+o);
			System.out.println(o.age());//获取注解中的属性
		}
	}

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

@Target(ElementType.TYPE)
//表明只能注解类
@Retention(RetentionPolicy.RUNTIME)
//.RUNTIME表示可以被反射获取
public @interface MyAnnotation {
	int age() default 21;
}

(五)注解的作用

如通过注解判断Student类中是否存在age属性

public class test {
	public static void main(String[] args) throws  Exception{
		Class studentClass=Class.forName("test.Student");
		if (studentClass.isAnnotationPresent(AgeAnnotation.class)) {
			Field[] fs=studentClass.getFields();
			for (Field f:fs) {
				if ("age".equals(f.getName())) {
					System.out.println("age属性存在");
					break;
				}
			}
		}
	}
}

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

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface AgeAnnotation {

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值