注解与反射

注解

标记某个被注解的东西(类, 方法等),让其他程序根据这个东西上面的注解信息来执行对他的操作

元注解

  • Target

Target作用域

  • Retention

Retention保留

  • Documented:表示注解是否被 javadoc 工具记录,默认情况下注解是不包含在 javadoc 中的。
  • Inherited:表示注解是否可以被继承,默认情况下注解是不会被子类继承的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 自定义注解
@Target({ElementType.METHOD, ElementType.LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Person {
String name() default "";
int age();
}

class test {

@Person(age = 20)
private static final int a = 100;

@Person(age = 18, name = "fred")
public String eat(String food) {
return food;
}

public static void main(String[] args) {
try {
Method eat = test.class.getMethod("eat", String.class);
if (eat.isAnnotationPresent(Person.class)) { //判断该元素上是否有Person注解
Person person = eat.getAnnotation(Person.class);//获取方法上的注解
String name = person.name();
int age = person.age();
System.out.println(name + " " + age);
}

Field a1 = test.class.getDeclaredField("a"); //反射获取字段
Person personOnA = a1.getAnnotation(Person.class);
System.out.println(personOnA.age());
} catch (NoSuchMethodException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//junit 源码
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Test {
Class<? extends Throwable> expected() default None.class;

long timeout() default 0L;

public static class None extends Throwable {
private static final long serialVersionUID = 1L;

private None() {
}
}
}

反射

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 获取类的class对象
Class<?> clazz = MyClass.class;

MyClass obj = new MyClass();
Class<?> clazz = obj.getClass();

Class<?> clazz = Class.forName("com.example.MyClass");

// 获取所有公共方法,包括继承的公共方法
Method[] methods = clazz.getMethods();

// 获取所有声明的方法(包括私有),不包括继承的方法
Method[] declaredMethods = clazz.getDeclaredMethods();

// 获取特定参数类型的方法,获取不到私有方法
Method method = clazz.getMethod("methodName", String.class);

// 获取字段
Field field = clazz.getDeclaredField("fieldName");

// 获取字段的值
Object value = field.get(obj);

// 设置字段的值
field.set(obj, "newValue");

注解与反射
https://payfish.github.io/2024/06/28/注解与反射/
作者
fu1sh
发布于
2024年6月28日
许可协议