Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

Java: Difference between Class.forName and ClassLoader.loadClass

What is the difference between Class.forName and ClassLoader.loadClass in the following codes:

Class theClass = Class.forName("SomeImpl");
SomeImpl impl = (SomeImpl)theClass.newInstance();

and

Class theClass = ClassLoader.loadClass("SomeImpl");
SomeImpl impl = (SomeImpl)theClass.newInstance();

Are they synonymous? Is one preferable to the other in certain circumstances? What are the do's and dont's when using these two methods?

question from:https://stackoverflow.com/questions/8345220/java-difference-between-class-forname-and-classloader-loadclass

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Class.forName() will always use the ClassLoader of the caller, whereas ClassLoader.loadClass() can specify a different ClassLoader. I believe that Class.forName initializes the loaded class as well, whereas the ClassLoader.loadClass() approach doesn't do that right away (it's not initialized until it's used for the first time).

Just found this article when looking to confirm my summary of the initialization behavior. It looks like this has most of the information you're looking for:

http://www.javaworld.com/javaworld/javaqa/2003-03/01-qa-0314-forname.html

This usage is pretty cool, though I've never used it before:

Class.forName(String, boolean, ClassLoader)

It allows you to specify a ClassLoader and the boolean parameter defines whether the class should be initialized when it's loaded or not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...