获取springboot中指定目录下 带有指定注解的类
private List<String> getTableNameList(){ List<String> list = new ArrayList<>(); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); //获取 包路径 classPath*: classpath*:com/lyc/**/*DO.class String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath("com.lyc") +"/**/*DO.class"; try { Resource[] resources = resolver.getResources(pattern); CachingMetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resolver); for (Resource resource : resources){ MetadataReader metadataReader = readerFactory.getMetadataReader(resource); // 扫描到的class String className = metadataReader.getClassMetadata().getClassName();
// 这边已经获取到类信息了,但是我这边需要的是注解里面的信息 Class<?> clazz = Class.forName(className); TableName annotation = clazz.getAnnotation(TableName.class); if ( annotation != null){ list.add(annotation.value()); } } } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } return list; }
使用场景:获取TableName注解下面的所有表名
https://blog.csdn.net/sinat_39314995/article/details/107412600?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-107412600-blog-110822674.pc_relevant_layerdownloadsortv1&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-1-107412600-blog-110822674.pc_relevant_layerdownloadsortv1&utm_relevant_index=2