Java Reflections 依赖

reflections-0.9.11

<!-- https://mvnrepository.com/artifact/org.reflections/reflections -->
<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.11</version>
</dependency>

 

guava-30.1.1-jre

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>30.1.1-jre</version>
</dependency>

 

javassist-3.27.0-GA

<!-- https://mvnrepository.com/artifact/org.javassist/javassist -->
<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.27.0-GA</version>
</dependency>

 例:

// com.coding 包下的所有带有ClassTag注解的类
    @Test
    public void testAnnotationType() {
        org.reflections.Reflections reflections = new org.reflections.Reflections("com.coding");
        //Stopwatch stopwatch = Stopwatch.createStarted();
        Set<Class<?>> classes = reflections.getTypesAnnotatedWith(ClassTag.class);
        //System.out.println(stopwatch.toString());
        for (Class type : classes) {
            System.out.println("Found:" + type.getName());
        }
    }
// 所有带MethodMarker注解的方法
    @Test
    public void testAnnotationMethod() {
        org.reflections.Reflections reflections = new org.reflections.Reflections(new ConfigurationBuilder()
                .setUrls(ClasspathHelper.forPackage("com.coding")).addScanners(new MethodAnnotationsScanner()));

        Set<Method> annotatedWith = reflections.getMethodsAnnotatedWith(MethodMarker.class);

        for (Method p : annotatedWith) {
            // logger.info(clazz.getName());
            System.out.println("Found: " + p.getName());
        }
    }
// 所有properties文件
    @Test
    public void testResource() {
        org.reflections.Reflections reflections = new org.reflections.Reflections(new ConfigurationBuilder()
                .setUrls(ClasspathHelper.forPackage("com.coding")).addScanners(new ResourcesScanner()));

        Set<String> properties = reflections.getResources(Pattern.compile(".*\\.properties"));

        for (String p : properties) {
            // logger.info(clazz.getName());
            System.out.println("Found: " + p);
        }
    }

 

posted @ 2022-07-25 17:40  SilentKiller  阅读(237)  评论(0)    收藏  举报