[英]List all classes in a package that implements a given interface
I want to list/enumerate (at runtime) in my Java program all classes that implements a given interface, and retrieve the class name. 我想在我的Java程序中列出/枚举(在运行时)实现给定接口的所有类,并检索该类的名称。 Is it possible ? 可能吗 ? How can i do ? 我能怎么做 ?
To elaborate on how to do that using reflection : 要详细说明如何使用反射来做到这一点:
You can start off with Thread.currentThread().getContextClassLoader()
. 您可以从Thread.currentThread().getContextClassLoader()
。 Using a package name as path, get at the resources : Enumeration<URL> resources = classLoader.getResources(path);
使用包名称作为路径,获取资源: Enumeration<URL> resources = classLoader.getResources(path);
Then you would have to decode the filenames from the resources, and iterate over them (recursively as some might be directories). 然后,您将不得不从资源中解码文件名,并对其进行迭代(递归,因为某些文件可能是目录)。 Filter the resources for .class
files, instantiate the classes with Class.forName()
and check the interfaces they implement. 过滤.class
文件的资源,使用Class.forName()
实例化类,并检查它们实现的接口。
You should use java Reflection 您应该使用Java Reflection
This link offers a tutorial that cover all the thing you can do using Reflection. 该链接提供了一个教程,涵盖了您使用反射可以做的所有事情。 You can build your code starting from there 您可以从此处开始构建代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.