JavaReflection returns a list of classes that implement a specific interface

I have a package that contains an interface and several classes, some classes in this package implement this interface. In one class that does not implement this interface, I want to write a method that returns an object of all classes that implement this interface, I don’t know the names of the classes that implement this interface, how can I write this method?

+3
source share
3 answers

As a rule, such a function is absent in the java mapping API. but you can probably implement it yourself quite easily.

systemp java.class.path classpath. path.separator. , jar JAR API, , AssignableFrom (theClass).

, BSF, . , . : jar. , , .

private static Map<String, Boolean> getEngines() throws Exception {
    Map<String, Boolean> result = new HashMap<String, Boolean>();
    String[] pathElements = System.getProperty("java.class.path").split(System.getProperty("path.separator"));
    for (String pathElement : pathElements) {
        File resource = new File(pathElement);
        if (!resource.isFile()) {
            continue;
        }
        JarFile jar = new JarFile(resource);
        for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
            JarEntry entry = e.nextElement();
            if(entry.isDirectory()) {
                continue;
            }
            if(!entry.getName().endsWith("Engine.class")) {
                continue;
            }
            String className = entry.getName().replaceFirst("\\.class$", "").replace('/', '.');
            try {
                if(BSFEngine.class.getName().equals(className)) {
                    continue;
                }
                Class<?> clazz = Class.forName(className);
                if(BSFEngine.class.isAssignableFrom(clazz) && !clazz.equals(BSFEngine.class)) {
                    result.put(className, true);
                }
            } catch (NoClassDefFoundError ex) {
                // ignore...
                result.put(className, false);
            }
        }
    }
    return result;
}

Map, , , . , .

+1

, reflections.

, :

Reflections reflections = new Reflections("my.project.prefix");

Set<Class<? extends SomeClassOrInterface>> subTypes =
    reflections.getSubTypesOf(SomeClassOrInterface.class);
+2

, , . .getInterfaces() .

, , , .

0

Source: https://habr.com/ru/post/1771242/


All Articles