获取在包中声明的所有Java类的名称 [英] Getting the names of all Java classes declared in a package
问题描述
我正在写一个功能,这将有助于在我的程序的某个包中获取类。此外,我只想要一个类的子类的某个类。
我需要类为了调用静态方法。
有自动的方法吗?
如果我不清楚,我想要的是这样的:
ArrayList< Class< ;? extends MySuperClass>> classes =;
classes.add(MyClass.class);
classes.add(MyClass2.class);
而不是必须为每个类调用add,我想自动获得该类列表。 / p>
类的数量很小,所以我不介意自动手动声明它们,如果自动技巧会很慢 - 这个应用程序是一个移动平台。
无论如何,我也想知道如何为ArrayList中的每个方法调用静态方法:
// error类的方法nameOfStaticMethod未定义类< capture#2-of? extends MySuperClass>
classes.get(0).nameOfStaticMethod();感谢您的意见。 解决方案 Java不提供此功能。在包级别没有内省。这些类可以是数据库中的记录,或者是网络连接的另一侧。
您可以使用自定义类加载器和API来提供一种方法来列出类名。
I'm writing a functionality where it would be helpful to get the classes inside a certain package of my program. Also, I only want the classes that subclass a certain class.
I need the classes in order to call static methods on them.
Is there an automatic way to do this? If so, is it slow?
In case I was not clear, what I want is something like this:
ArrayList<Class<? extends MySuperClass>> classes = ;
classes.add(MyClass.class);
classes.add(MyClass2.class);
Instead of having to call add for each class, I would like to automatically get that class list.
The number of classes is small, so I would not mind declaring them manually if the automatic trick would be slow - this app is for a mobile platform.
In either way, I would also like to know how to call the static method for each method in the ArrayList:
// error The method nameOfStaticMethod is undefined for the type Class<capture#2-of ? extends MySuperClass>
classes.get(0).nameOfStaticMethod ();
Thanks for your comments.
解决方案 Java doesn't provide this ability. There is no introspection at the package level. The classes could be records in a database, or on the other side of a network connection. There's no requirement for them to be stored and organized so as to facilitate enumerating them by package.
You could make a custom class loader and API to provide a method of listing the class names.
这篇关于获取在包中声明的所有Java类的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!