Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if class exists in Java classpath without running its static initializer?

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?

like image 851
Epaga Avatar asked Aug 12 '10 10:08

Epaga


People also ask

How do you know if a class is present in classpath?

We can check for the existence of a class using Java Reflection, specifically Class. forName(). The documentation shows that a ClassNotFoundException will be thrown if the class cannot be located.

How do I know if my classpath is set correctly?

To check our CLASSPATH on Windows we can open a command prompt and type echo %CLASSPATH%. To check it on a Mac you need to open a terminal and type echo $CLASSPATH.

How do I know if a jar is in classpath?

A pragmatic way: Class. forName("com. myclass") where com. myclass is a class that is inside (and only inside) your target jar; if that throws a ClassNotFoundException , then the jar is not on you current classpath.


1 Answers

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

JavaDoc link

like image 189
André Avatar answered Sep 19 '22 06:09

André