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

Epa*_*aga 62 java class classloader

如果我使用

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

"Foo"的静态初始化程序块启动.有没有办法确定类"my.package.Foo"是否在类路径上而没有启动其静态初始化程序?

And*_*dré 81

尝试使用forName(String name, boolean initialize, ClassLoader loader)方法Class并将参数设置initializefalse.

JavaDoc链接

  • 应该管用.根据API:仅当initialize参数为true且之前尚未初始化时,才初始化类. (3认同)
  • 你知道我在谷歌搜索中找到的所有结果,你是唯一一个提到初始化参数的人 - 如果只是测试一个类的存在(他通常不想加载),对我来说似乎是件大事它想知道为什么其他人都懒得提起它. (3认同)
  • `ClassLoader`参数一般应设置为`this.getClass().getClassLoader()`? (2认同)