Phil
Phil

Reputation: 909

In Java, can Class.forName ever return null?

In Java, can Class.forName ever return null, or will it always throw a ClassNotFoundException or NoClassDefFoundError if the class can't be located?

Upvotes: 6

Views: 4322

Answers (4)

willcodejavaforfood
willcodejavaforfood

Reputation: 44063

Java Docs says it will throw ClassNotFoundException if the class cannot be found so I'd say it never returns null.

Upvotes: 12

Miserable Variable
Miserable Variable

Reputation: 28752

@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

Upvotes: -2

Piko
Piko

Reputation: 4122

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

Upvotes: 0

Dan Dyer
Dan Dyer

Reputation: 54465

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.

Upvotes: 5

Related Questions