In Java, can Class.forName ever return null?

放肆的年华 提交于 2019-12-01 04:18:40

问题


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


回答1:


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




回答2:


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.




回答3:


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




回答4:


@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



来源:https://stackoverflow.com/questions/430089/in-java-can-class-forname-ever-return-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!