In Java, can Class.forName ever return null, or will it always throw a ClassNotFoundException or NoClassDefFoundError if the class can't be located?
Since null is not mentioned anywhere in the documentation for this method and because there doesn't seem to be any situation in which it would make sense for the method to return null instead of throwing an exception, I think it's pretty safe to assume that it never returns null.
It won't throw a NoClassDefFoundError, but it may throw ClassNotFoundException.
Java Docs says it will return ClassNotFoundException if the class cannot be found so I'd say it never returns null.
Using the default class loader, surely you will receive no nulls. But, as jdigital says, you may be subject to any number of custom classloaders depending on what security model or other type of proxy loader that you may be using (intentionally or otherwise).
Heck, even forName can take a ClassLoader as a parameter... :)
Piko
@Dan Dyer is wrong, Class.forName can throw NoClassDefFoundError
, if the class it is trying gets a ClassNotFoundException error in its static initialiazer. The following is unte
class Outer {
public static final void main(final String[] args) throws Exception{
Class.forName("Inner");
}
}
If you compile and run this in a directory with no other file you get ClassNotFoundException: Inner
Now add the following to in the same directory, compile everything and java Outer
once to see it runs ok.
class Inner {
static Inner2 _i2 = new Inner2();
}
class Inner2 {}
Finally, delete Inner2.class and rerun Outer, you will get NoClassDefFoundError: Inner2
, caused by ClassNotFoundException: Inner2