概述
优点
结构
格式
- public @interface 注解名称 {
public 属性类型 属性名() default 默认值 ;
} - 默认值可以不写
- 没有值的属性,在使用时,要给予初始值
注解的数据类型
- 基本数据类型
- String
- Class
- 注解
- 枚举
- 以上类型的一维数
元注解:修饰注解的注解
- 元注解就是描述注解的注解
- 类型
- @Target :指定了注解能在哪里使用
- @Retention :可以理解为保留时间(生命周期)
- @Inherited:表示修饰的自定义注解可以被子类继承
- @documented :表示该自定义注解,会出现在API文档里面。
注解的使用
package _11注解;
import java.lang.annotation.*;
//元注解----在类使用
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface VIP {
public int leval() default 1;
public String name();
}
package _11注解;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//元注解-----在方法前有效
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Run {
}
package _11注解;
@VIP(leval = 3, name = "a")
public class Gaming {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Run
public void play() {
System.out.println("Run注解的被注解的运行了");
}
@Override
public String toString() {
return "Gaming{" +
"name='" + name + ''' +
", age=" + age +
'}';
}
}
package _11注解;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.linkedList;
public class Main {
public static void main(String[] args) throws Exception {
//让注解生效
Gaming game = new Gaming();
//通过反射获得注解,根据注解的类型进行不同处理
//1.在运行类时,被Run注解的方法运行
//获得字节码类对象
Class aClass = game.getClass();
//获得方法
Method[] declaredMethods = aClass.getDeclaredMethods();
for (Method method : declaredMethods) {
//将方法更改为可操作
method.setAccessible(true);
//获得方法上的注解
Run annotation = method.getAnnotation(Run.class);
//存在Run注解的方法则运行
if(annotation != null){
method.invoke(game);
}
}
//2.根据类注解上的VIP注解,做出不同的效果
//根据字节码类对象,反射获得其类注解---要强制转换为VIP注解类型
VIP annotation = (VIP)aClass.getAnnotation(VIP.class);
//根据VIP注解上的等级不同。做出不同反应
if(annotation.leval() == 1){
System.out.println("VIP注解可以玩1小时");
}else if(annotation.leval() == 2){
System.out.println("VIP注解可以玩2小时");
}else if(annotation.leval() == 3){
System.out.println("VIP注解可以玩3小时");
}else{
System.out.println("VIP注解可以玩5小时");
}
}
}
总结
- 注解要进行定义,再在相应的地方使用
- 搭配反射技术,再检测到相关注解的地方,再进行相应的注解处理代码