我想知道是否有任何给定的函数允许我自省一个类,而不必编写包含该类的包。
例如,我想查看Integer类的方法和超类,为此我必须指定该类所在的包。这将是“java.lang.Integer”
而不是这样做,我只想输入类名以显示类的信息。就像这个“整数”
我怎样才能让我的程序只检查类名,不管它在哪里?
我想知道是否有任何给定的函数允许我自省一个类,而不必编写包含该类的包。
例如,我想查看Integer类的方法和超类,为此我必须指定该类所在的包。这将是“java.lang.Integer”
而不是这样做,我只想输入类名以显示类的信息。就像这个“整数”
我怎样才能让我的程序只检查类名,不管它在哪里?
Java 不会阻止您创建自己的my.company.Integer
类和my.other.company.Integer
类,因此它无法知道哪个Integer
类是正确的。
我可以建议的答案的最接近的事情是创建一个预定义的包列表,您要在其中搜索类,并继续尝试每个包,直到找到您的类。
所以像:
class ClassFinder{
public static final String[] searchPackages = {
"java.lang",
"java.util",
"my.company",
"my.company.other" };
public Class<?> findClassByName(String name) {
for(int i=0; i<searchPackages.length; i++){
try{
return Class.forName(searchPackages[i] + "." + name);
} catch (ClassNotFoundException e){
//not in this package, try another
} catch (...){
//deal with other problems...
}
}
//nothing found: return null or throw ClassNotFoundException
return null;
}
}
如果您想获取所有可用包的列表而不是对其进行硬编码,请参阅此处。
请注意,此方法不太可能执行得很好,因此请谨慎使用。
/**
* Returns first loaded Class found in the searchPackages
* @param classname the simple class name (e.g. "String")
* @param searchPackages String[] of packages to search.
* <li>Place the more important packages at the top since the first Class
* found is returned</li>
* <code>//Example
* public static final String[] searchPackages = {
* "java.lang",
* "java.util",
* "my.company",
* "my.company.other" };
* </code>
* @return the loaded Class or null if not found
*/
public static final Class<?> findClassByName(String classname, String[] searchPackages) {
for(int i=0; i<searchPackages.length; i++){
try{
return Class.forName(searchPackages[i] + "." + classname);
} catch (ClassNotFoundException e){
//not in this package, try another
}
}
//nothing found: return null or throw ClassNotFoundException
return null;
}
/**
* Returns the loaded Class found in the searchPackages
* @param classname the simple class name (e.g. "String")
* @param searchPackages String[] of packages to search.
* <li>Place the more important packages at the top since the first Class
* found is returned</li>
* <code>//Example
* public static final String[] searchPackages = {
* "java.lang",
* "java.util",
* "my.company",
* "my.company.other" };
* </code>
* @throws RuntimeException if more than one class of the same classname found in multiple packages
* @return the loaded Class (guaranteed to be unique among the searchPackages) or null if not found
*/
public static final Class<?> findClassByNameNoDupes(String classname, String[] searchPackages) {
Class<?> foundClass = null;
for(int i=0; i<searchPackages.length; i++){
try{
boolean wasNull = foundClass == null;
foundClass = Class.forName(searchPackages[i] + "." + classname);
if (!wasNull) throw new RuntimeException(classname + " exists in multiple packages!");
} catch (ClassNotFoundException e){
//not in this package, try another
}
}
return foundClass;
}
这是不可能的,类一旦被引用就会动态加载。因此,没有办法深入了解可用包的列表,因为没有这样的东西。
但是,有一些方法可以检查 jar,因为这些是 zip 文件(包括标准 JVM jar)。