反射Reflections
Reflections通过扫描classpath,索引元数据,并且允许在运行时查询这些元数据。
使用Reflections可以很轻松的获取以下元数据信息:
1)获取某个类型的所有子类;比如,有一个父类是TestInterface,可以获取到TestInterface的所有子类。
2)获取某个注解的所有类型/字段变量,支持注解参数匹配。
3)使用正则表达式获取所有匹配的资源文件
4)获取特定签名方法。
通常的用法有:
引入依赖jar
org.reflections reflections 0.9.10
项目中使用:
// 初始化工具类
//Reflections reflections = new Reflections(new ConfigurationBuilder().forPackages(basePackages).addScanners(new SubTypesScanner()).addScanners(new FieldAnnotationsScanner()));
Reflections reflections = new Reflections("com.boot.security.server.dao", new MethodAnnotationsScanner(), new TypeAnnotationsScanner(), new SubTypesScanner(), new MethodParameterNamesScanner());
// 获取某个包下类型注解对应的类
Set> typeClass = reflections.getTypesAnnotatedWith(RpcInterface.class, true);
// 获取子类
Set> subTypes = reflections.getSubTypesOf(SomeType.class);
// 获取注解对应的方法
Set resources =reflections.getMethodsAnnotatedWith(SomeAnnotation.class);
// 获取注解对应的字段
Set ids = reflections.getFieldsAnnotatedWith(javax.persistence.Id.class);
// 获取特定参数对应的方法
Set someMethods = reflections.getMethodsMatchParams(long.class, int.class);
Set voidMethods = reflections.getMethodsReturn(void.class);
Set pathParamMethods =reflections.getMethodsWithAnyParamAnnotated(PathParam.class);
// 获取资源文件
Set properties = reflections.getResources(Pattern.compile(".*\\.properties"));
具体也可以参见官方文档:https://www.programcreek.com/java-api-examples/index.php?api=org.reflections.scanners.MethodAnnotationsScanner
Method方法:
getDeclaringClass 返回clazz
method.getDeclaringClass().getName() 返回方法所属类名
/**
* {@inheritDoc}
*/
@Override
public Class<?> getDeclaringClass() {
return clazz;
}
method.getDeclaringClass().getName()+"."+method.getName()