获取指定包下某个注解的所有方法并提取注解信息

package org.jeecg;


import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Controller;

import java.lang.reflect.Method;
import java.util.Set;

/**
 * @descriptions:
 * @author: LZH
 * @date: 2021/8/11/011 19:30
 * @version: 1.0
 */
public class AnnotationUtil {
    public static void main(String[] args) {
        findAnnotatedClasses("org.jeecg.modules");
    }

    private static void findAnnotatedClasses(String scanPackage) {
        Set<BeanDefinition> candidateComponents = createComponentScanner().findCandidateComponents(scanPackage);
        for (BeanDefinition candidateComponent : candidateComponents) {
            validAnnotation(candidateComponent.getBeanClassName());
        }
        /*candidateComponents.stream().map(beanDef -> {
            return null;
        });*/
    }

    private static ClassPathScanningCandidateComponentProvider createComponentScanner() {
        // Don't pull default filters (@Component, etc.):
        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
        provider.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
        return provider;
    }


    public static void validAnnotation(String clsName) {
        Class<?> cls = null;
        try {
            cls = Class.forName(clsName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        if (cls == null) {
            return;
        }
        //获取类中的所有的方法
        Method[] methods = cls.getMethods();
        for (Method method : methods) {
            RequiresPermissions annotation = method.getAnnotation(RequiresPermissions.class);
            ApiOperation apiAnnotation = method.getAnnotation(ApiOperation.class);
            if (annotation==null || apiAnnotation==null){
                continue;
            }
            String[] permissionValue = annotation.value();
            String aipValue = apiAnnotation.value();
            StringBuilder sb = new StringBuilder();
            for (String ele : permissionValue) {
                sb.append(ele);
            }
            System.out.println(sb);
            System.out.println(aipValue);
            //保存 
        }
        
    }


}

你可能感兴趣的:(java,java)