简体   繁体   English

有没有办法获得实现特定方法的所有类?

[英]Is there a way to get all the classes that implement a certain method?

The title speaks for itself. 标题不言而喻。 The language is Java. 语言是Java。

Yes, there is. 就在这里。 This is however a tedious and expensive work. 然而,这是繁琐且昂贵的工作。 You need to crawl through all class files and all JAR files with help of ClassLoader#getResources() and a shot of java.io.File and load all classes of it with help of Class#forName() and finally check if the method is there by Class#getMethod() . 您需要在ClassLoader#getResources()java.io.File帮助下对所有类文件和所有JAR文件进行爬网,并在Class#forName()帮助下加载其所有类,最后检查方法是否为通过Class#getMethod()

However, there are 3rd party API's which can take the tedious work from hands, but it is still expensive, because loading a class would cause its static initializers being executed. 但是,有一些第三方API可以处理繁琐的工作,但是它仍然很昂贵,因为加载类将导致其static初始化程序被执行。

A cleaner way is to make use of annotations and annotate the methods in question and then make use of libraries which searches for classes/methods/fields based on the annotations, such as Google Reflections . 一种更干净的方法是利用annotations并注释所讨论的方法,然后利用基于批注搜索类/方法/字段的库,例如Google Reflections

On the other hand, if the entire package name or the JAR file name is known beforehand, then the work will be less tedious and expensive (no need to do stuff recursively nor to load the all of the classes of entire classpath). 另一方面,如果事先知道整个程序包名称或JAR文件名,则工作将不再那么繁琐和昂贵(无需递归地进行操作或加载整个classpath的所有类)。

Update: I remember, I ever wrote sample code to achieve something like that, you can find it here . 更新:我记得,我曾经写过示例代码来实现类似的目的,您可以在这里找到它。 It's good to start with, you only need to change it a bit to check the method. 首先很好,您只需稍作更改即可检查方法。

No, you can't, in general. 不,您通常不能。 If you could get a complete list of available classes you could check each of them using reflection - but you can't ask a classloader for a list of everything that's available. 如果您可以获得可用类的完整列表,则可以使用反射检查每个类-但您不能要求类加载器提供所有可用类的列表。 (For instance, it may be fetching classes over HTTP, and may not know all the files available.) (例如,它可能正在通过HTTP获取类,并且可能不知道所有可用文件。)

If you knew that you were interested in classes in a jar file, however, you could open the jar file, find all the class files within it and ask the classloader for those classes. 但是,如果您知道您对jar文件中的类感兴趣,则可以打开jar文件,找到其中的所有类文件,然后向类加载器询问这些类。 It would be somewhat fiddly. 这会有点古怪。

What's the bigger picture here? 这里的大局是什么? There may be a better way to approach the problem. 解决这个问题可能有更好的方法。

Also, in Eclipse , you can simply ask for this : 另外,在Eclipse中 ,您可以简单地要求:

Clic on the method, and type Ctrl-T . 选中该方法,然后键入Ctrl-T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM