在Jar中查找实现接口的类 [英] Find classes implementing an interface in Jar

查看:1517
本文介绍了在Jar中查找实现接口的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找出jar中的类是否实现了特定的接口。我已经实现了下面的代码,但它遍历jar文件中的所有类,并在每个类上查找它是否已实现此特定接口。

I want to find whether the classes inside the jar has implemented a particular interface or not. I have implemented below code, but it iterates over all the classes inside jar file and finds on each class whether it has implemented this particular interface or not.

    public static synchronized boolean findClassesInJar(final Class<?> baseInterface, final String jarName){
        final List<String> classesTobeReturned = new ArrayList<String>();
        if (!StringUtils.isBlank(jarName)) {
            //jarName is relative location of jar wrt. 
            final String jarFullPath = File.separator + jarName;
            final ClassLoader classLoader = this.getClassLoader();
            JarInputStream jarFile = null;
            URLClassLoader ucl = null;
            final URL url = new URL("jar:file:" + jarFullPath + "!/");
            ucl = new URLClassLoader(new URL[] { url }, classLoader);
            jarFile = new JarInputStream(new FileInputStream(jarFullPath));
            JarEntry jarEntry;
            while (true) {
                jarEntry = jarFile.getNextJarEntry();
                if (jarEntry == null)
                    break;
                if (jarEntry.getName().endsWith(".class")) {
                    String classname = jarEntry.getName().replaceAll("/", "\\.");
                    classname = classname.substring(0, classname.length() - 6);
                    if (!classname.contains("$")) {
                        try {
                            final Class<?> myLoadedClass = Class.forName(classname, true, ucl);
                            if (baseInterface.isAssignableFrom(myLoadedClass)) {
                                return true;
                            }
                        } catch (final ClassNotFoundException e) {

                        } 
                    }
                }
            }
        return false;
    }

有没有简单的方法可以做到这一点?因为如果有一个包含100个类文件且第100个类的jar已经实现了这个接口,通过上面的代码,我需要迭代所有100个类文件并查找它是否已经实现了接口。有没有有效的方法呢?

Is there any simple way to do this ? Because If have a jar with 100 class files and 100th class has implemented this interface, through the above code I need to iterate all the 100 class files and find whether it has implemented the interface or not. Is there any efficient way of doing it ?

推荐答案

思考库可以做到这一点:

Reflections reflections = new Reflections(
    ClasspathHelper.forPackage("your.root.package"), new SubTypesScanner());
Set<Class<? extends YourInterface>> implementingTypes =
     reflections.getSubTypesOf(YourInterface.class);

这篇关于在Jar中查找实现接口的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆