70

If I use

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

the static initializer block of "Foo" is kicked off. Is there a way to determine whether a class "my.package.Foo" is on the classpath without kicking off its static initializer?

Epaga
  • 38,231
  • 58
  • 157
  • 245

1 Answers1

93

Try the forName(String name, boolean initialize, ClassLoader loader) method of Class and set the param initialize to false.

JavaDoc link

carlspring
  • 31,231
  • 29
  • 115
  • 197
André
  • 2,313
  • 2
  • 25
  • 29
  • 3
    Should work. According to the API: The class is initialized only if the initialize parameter is true and if it has not been initialized earlier. – aioobe Aug 12 '10 at 10:16
  • 2
    The `ClassLoader` parameter should be generally set to `this.getClass().getClassLoader()`? – aliteralmind Apr 23 '14 at 00:35
  • 3
    you know of all the results I found in a google search, you're the only one who mentions the initialize parameter - seems a big thing to me if one is just testing the existence of a class (he'd not want to usually load it), wonder why the other people didn't bother to mention it. – ycomp Oct 13 '15 at 18:37
  • Contrary to @aliteralmind Java itself [sets](https://zgrepcode.com/java/openjdk/10.0.2/java.base/java/lang/class.java#L-287) this parameter to ` Reflection.getCallerClass()` – Mark Jeronimus Sep 03 '18 at 08:02