简体   繁体   中英

Finding classes with ClassPath.getTopLevelClasses() in jar packaged by spring-boot-maven-plugin

The spring-boot-maven-plugin packages all of "my" classes and 3rd party libraries under BOOT-INF/classes.com.my.package.MyClass.class

This makes it impossible to find them with ClassPath.getTopLevelClasses("com.my.package") as normally works.

I can find them with ClassPath.getTopLevelClasses("BOOT-INF.classes.com.my.package") but the class can't be instantiated with that name.

Unfortunately, this package scanning happens in a library and not in my code so I can't change it. The only thing I can do is configure where to search for my classes.

Is there any way of having the spring-boot-maven-plugin package my classes along with its own, outside of BOOT-INF? Or is there any other way around this?

private final static String TARGET_PACKAGE = "com.my.package";
private final String SPRING_BOOT_PREFIX = "BOOT-INF.classes.";

private Set<ClassInfo> getClassInfoSet() {
    try {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        Set<ClassInfo> classInfoSet = ClassPath.from(loader).getTopLevelClasses(TARGET_PACKAGE);
        if (classInfoSet.isEmpty()) {
            classInfoSet = ClassPath.from(loader).getTopLevelClasses(SPRING_BOOT_PREFIX + TARGET_PACKAGE);
        }
        return classInfoSet;
    }
    catch (IOException e) {
        return Collections.emptySet();
    }
}

private String getClassName(ClassInfo classInfo) {
    String className = classInfo.getName();
    if (className.contains(SPRING_BOOT_PREFIX)) {
        return StringUtils.substringAfterLast(className, SPRING_BOOT_PREFIX);
    }
    return className;
}

// you can get the Class now
Class.forName(getClassName(classInfo));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM