selfAnnotation annotation = pClass.getAnnotation(selfAnnotation.class);
System.out.println(annotation.type());
}
}
}
@selfAnnotation(type = 2)
class
【一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义】
浏览器打开:qq.cn.hn/FTf 免费领取
persson{
private int num;
public int getNum(){
return this.num;
}
}
//第三步:添加元注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
//第一步:定义注解
@interface selfAnnotation{
//第二步:定义参数
int type() default 1;
}
三、读取方法参数的注解
我们都知道,一个函数的参数可以是多个,而一个参数的注解也可以是多个,所以,我们获取到的 参数的注解是一个二维数组,即第几个参数的第几个注解
package test;
import java.lang.annotation.*;
import java.lang.reflect.Method;
import java.util.Arrays;
public class changeData {
public static void main(String[] args) {
Class pClass = persson.class;
try {
Method method_getNum = pClass.getMethod(“getNum”, int.class);
Annotation[][] parameterAnnotations = method_getNum.getParameterAnnotations();
System.out.println(Arrays.toString(parameterAnnotations[0]));
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
class persson{
private int num;
public int getNum(@two @one int a){
return this.num;
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@interface one{
int type() default 1;
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
@interface two{
int value() default 2;
}
四、使用注解
注解如何使用,完全由程序自己决定。例如,JUnit是一个测试框架,它会自动运行所有标记为@Test
的方法。
我们来看一个@Range
注解,我们希望用它来定义一个String
字段的规则:字段长度满足@Range
的参数定义:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Range {
int min() default 0;
int max() default 255;
}
在某个JavaBean中,我们可以使用该注解:
public class Person {
@Range(min=1, max=20)
public String name;
@Range(max=10)
public String city;
}
但是,定义了注解,本身对程序逻辑没有任何影响。我们必须自己编写代码来使用注解。这里,我们编写一个Person
实例的检查方法,它可以检查Person
实例的String
字段长度是否满足@Range
的定义:
void check(Person person) throws IllegalArgumentException, ReflectiveOperationException {
// 遍历所有Field:
for (Field field : person.getClass().getFields()) {
// 获取Field定义的@Range:
Range range = field.getAnnotation(Range.class);
// 如果@Range存在:
if (range != null) {
// 获取Field的值:
Object value = field.get(person);
// 如果值是String:
if (value instanceof String) {
String s = (String) value;
// 判断值是否满足@Range的min/max:
if (s.length() < range.min() || s.length() > range.max()) {
throw new IllegalArgumentException("Invalid field: " + field.getName());
}
}
}
}