/**
* Checks if a class can be found with the classloader.
* @param moduleName a Module.
* @param className the binary name of the class in question.
* @return true if the class can be found, otherwise false.
*/
private boolean classExists(String moduleName, String className) {
Optional<Module> module = ModuleLayer.boot().findModule(moduleName);
if(module.isPresent()) {
return Class.forName(module.get(), className) != null;
}
return false;
}
字符串 额外的好处:只接受一个参数的附加函数
/**
* Checks if a class can be found with the classloader.
* @param name the fully qualified name of the class in question.
* @return true if the class can be found, otherwise false.
*/
private boolean classExists(String name) {
int lastDot = name.lastIndexOf('.');
String moduleName = name.substring(0, lastDot);
String className = name.substring(lastDot+1);
return classExists(moduleName, className);
}
2条答案
按热度按时间q1qsirdb1#
尝试
Class
的forName(String name, boolean initialize, ClassLoader loader)
方法,并将参数initialize
设置为false
。JavaDoc链接
a14dhokn2#
自Java 9以来,有一个新的方法可以检查类是否存在,但在类不存在的情况下不会抛出异常,这应该是首选而不是预期的异常。
例如,这个函数在给定包和类名时检查类的存在:
字符串
额外的好处:只接受一个参数的附加函数
型
链接:相关JavaDoc