Use Java reflection to find classes that implement an interface from a package
2014-04-24 10:07
579 查看
How do you find a set of Classes that implement and interface? You do this (well, I did this).
And use this helper class:
final List<Class<?>> processorCandidates = ReflectionHelper.findClassesImpmenenting(HostDataProcessor.class, HostDataProcessor.class.getPackage());
And use this helper class:
public class ReflectionHelper { public static List<Class<?>> findClassesImpmenenting(final Class<?> interfaceClass, final Package fromPackage) { if (interfaceClass == null) { Debug.println("Unknown subclass."); return null; } if (fromPackage == null) { Debug.println("Unknown package."); return null; } final List<Class<?>> rVal = new ArrayList<Class<?>>(); try { final Class<?>[] targets = getAllClassesFromPackage(fromPackage.getName()); if (targets != null) { for (Class<?> aTarget : targets) { if (aTarget == null) { continue; } else if (aTarget.equals(interfaceClass)) { Debug.println("Found the interface definition."); continue; } else if (!interfaceClass.isAssignableFrom(aTarget)) { Debug.println("Class '" + aTarget.getName() + "' is not a " + interfaceClass.getName()); continue; } else { rVal.add(aTarget); } } } } catch (ClassNotFoundException e) { Debug.println("Error reading package name."); Debug.printStackTrace(e, Debug.LOW_LEVEL); } catch (IOException e) { Debug.println("Error reading classes in package."); Debug.printStackTrace(e, Debug.LOW_LEVEL); } return rVal; } /** * Load all classes from a package. * * @param packageName * @return * @throws ClassNotFoundException * @throws IOException */ public static Class[] getAllClassesFromPackage(final String packageName) throws ClassNotFoundException, IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); assert classLoader != null; String path = packageName.replace('.', '/'); Enumeration<URL> resources = classLoader.getResources(path); List<File> dirs = new ArrayList<File>(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); dirs.add(new File(resource.getFile())); } ArrayList<Class> classes = new ArrayList<Class>(); for (File directory : dirs) { classes.addAll(findClasses(directory, packageName)); } return classes.toArray(new Class[classes.size()]); } /** * Find file in package. * * @param directory * @param packageName * @return * @throws ClassNotFoundException */ public static List<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException { List<Class<?>> classes = new ArrayList<Class<?>>(); if (!directory.exists()) { return classes; } File[] files = directory.listFiles(); for (File file : files) { if (file.isDirectory()) { assert !file.getName().contains("."); classes.addAll(findClasses(file, packageName + "." + file.getName())); } else if (file.getName().endsWith(".class")) { classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6))); } } return classes; } }
相关文章推荐
- Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test java.lang.IllegalStateException
- a interface to stack that implement use the fixed array.
- How to use java dbus to create an Java Interface for dbus interface
- java.lang.SecurityException: Binder invocation to an incorrect interface 绑定错误的接口
- Security Tutorials系列第十二章:Building an Interface to Select One User Account from Many
- ERROR/AndroidRuntime(716): java.lang.SecurityException: Binder invocation to an incorrect interface
- 解决Failed to instantiate [java.util.List]: Specified class is an interface问题
- JavaUtils:1308 - Unable to find required classes (javax.activation.DataHandler and javax.ma il.
- How to implement an ArrayList structure in Java - Tutorial
- ubuntu package XXX needs to be reinstalled, but I can't find an archive 修复
- ERROR/AndroidRuntime(716): java.lang.SecurityException: Binder invocation to an incorrect interface
- javascript - C++, Qt, QtWebKit: How to create an html rendering window so that your application would get callbacks from JS calls? - Stack Overflow
- ajax上传图片TypeError: 'append' called on an object that does not implement interface FormData.
- ros-indigo卸载不全,出现The package <package name> needs to be reinstalled, but I can’t find an archive for
- Linux上运行maven项目报错Fatal Error: Unable to find package java.lang in classpath or bootclasspath
- mysql:If 'mysql' is not a typo you can use command-not-found to lookup the package that contains
- How to use an Outlook Object Model from Visual C++ by using a #import statement
- TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement.
- Java SE series:1. environment configure and Hello world! [We use compiler and packager to create an application!]
- Error This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. T