简体   繁体   English

列出实现给定接口的包中的所有类

[英]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.

相关问题 如何列出实现给定接口集的类路径上的所有类 - How to list all the classes on the class path that implements a given set of interfaces Java软件包扫描器-查找具有给定接口的所有类 - Java package scanner - find all classes with a given interface 具有实现接口的类的泛型的Java列表 - Java List with generics of Classes that implements an interface 为什么@resource可以找到所有类实现一个接口并将其作为列表注入 - Why @resource can find all classes implements an interface and inject them as a list 在Java多态中,是否可以将实现接口的所有类创建为该类型接口? - In Java polymorphism, can all the classes that implements an interface be created as that type interface? 如何为实现给定接口的所有类型注册通用JsonDeserializer - How to register generic JsonDeserializer for all types which implements given interface 获取实现给定接口的所有类 - Get all classes implementing given interface Byteman-跟踪给定包中的所有类和方法 - Byteman - trace all classes and methods in a given package 为什么实现Serializable接口的类没有实现接口的方法? - Why classes that implements Serializable interface implements none interface's methods? 识别对象实现的接口列表 - identify the list of interface a object implements
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM