检查类是否存在于Java类路径中,而不运行其静态初始化器?

tquggr8v  于 11个月前  发布在  Java
关注(0)|答案(2)|浏览(84)

如果我用

try {
      Class.forName("my.package.Foo");
      // it exists on the classpath
   } catch(ClassNotFoundException e) {
      // it does not exist on the classpath
   }

字符串
“Foo”的静态初始化器块被踢出。2有没有一种方法可以确定类“my.package.Foo”是否在类路径上而不踢出它的静态初始化器?

q1qsirdb

q1qsirdb1#

尝试ClassforName(String name, boolean initialize, ClassLoader loader)方法,并将参数initialize设置为false
JavaDoc链接

a14dhokn

a14dhokn2#

自Java 9以来,有一个新的方法可以检查类是否存在,但在类不存在的情况下不会抛出异常,这应该是首选而不是预期的异常。
例如,这个函数在给定包和类名时检查类的存在:

/**
 * 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);
}


链接:相关JavaDoc

相关问题