1. 导包
maven
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.11</version>
</dependency>
gradle
dependencies {
implementation 'org.reflections:reflections:0.9.11'
}
2. 布局
3. 文件内容流程
Quote: 用于指定找到文件被注解的文件.
GetPayContent: 自定义注解.
GateWay: 执行查看.
Automatic: 注解的文件, 含有执行方法的.
package com.ykenan.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 引用作用
*/
@Target(value = {ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Quote {
}
package com.ykenan.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value = {ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface GetPayContent {
/**
* 状态: 代表执行不同的方法, 实现不同的功能.
*
* @return int
*/
int status() default 0;
}
package com.ykenan.annotation;
import org.reflections.Reflections;
import java.lang.reflect.Method;
import java.util.Set;
public class GateWay {
public String gateWay(int status) {
// 返回的内容
String s = "";
// 指定包名, 不然扫描全部项目包, 包括引用的 jar
Reflections reflections = new Reflections("com.ykenan.annotation.quote");
// 获取带 Quote 注解的类
Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(Quote.class);
// 遍历
for (Class<?> clazz : typesAnnotatedWith) {
Method[] methods = clazz.getDeclaredMethods();
// 遍历方法
for (Method method : methods) {
// 判断带自定义注解 GetPayContent 的 method
if (method.isAnnotationPresent(GetPayContent.class)) {
GetPayContent annotation = method.getAnnotation(GetPayContent.class);
// 进行判断条件
if (annotation != null && annotation.status() == status) {
try {
// 执行 method, status 为方法传入的参数
s = (String) method.invoke(clazz.newInstance(), status);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
return s;
}
public static void main(String[] args) {
GateWay gate = new GateWay();
String a = gate.gateWay(0);
String b = gate.gateWay(1);
System.out.println(a);
System.out.println(b);
}
}
package com.ykenan.annotation.quote;
import com.ykenan.annotation.GetPayContent;
import com.ykenan.annotation.Quote;
@Quote
public class Automatic {
@GetPayContent
public String implA(int a) {
return "A" + a;
}
@GetPayContent(status = 1)
public String implB(int b) {
return "B" + b;
}
}