When use you use Class.forName("SomeImpl")
, you're obtaining the class via the current classloader (i.e. the loader of the class that you're making the method call in). It will also initialize the class. It's effectively the same as calling Class.forName("SomeImpl", true, currentLoader)
where currentLoader
would be the caller's classloader. See the details here.
The second method requires a classloader to be chosen first. Don't write it like ClassLoader.loadClass("SomeImpl")
since it is not a static method. You'd require something like
final ClassLoader cl = this.getClass().getClassLoader();
Class theClass = cl.loadClass("SomeImpl");
Mind that subclasses of ClassLoader should override the findClass method rather than loadClass
. This is the same as calling the (protected) method loadClass("SomeImpl", false)
, where the second argument indicates whether linking should be done or not.
There are more subtle differences... The loadClass
method expects a binary class name as specified by the Java Language Specification, while forName
could also be used with Strings representing primitive types or array classes.
Overal, it's best to use Class.forName
, if necessary specifying a specific classloader and whether it must be intialized or not, then let the implementation figure out the rest. Using classloaders directly is good for finding resources in a jar or on the classpath.