注解/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 {
}
2427

被折叠的 条评论
为什么被折叠?



