解释
在java中Class.forName()和ClassLoader都可以对类进行加载。ClassLoader就是遵循双亲委派模型最终调用启动类加载器的类加载器,实现的功能是“通过一个类的全限定名来获取描述此类的二进制字节流”,获取到二进制流后放到JVM中。Class.forName()方法实际上也是调用的CLassLoader来实现的
Class.forName(String className);这个方法的源码是
<tbody><tr><td class="gutter"><div class="line number1 index0 alt2">1</div><div class="line number2 index1 alt1">2</div><div class="line number3 index2 alt2">3</div><div class="line number4 index3 alt1">4</div><div class="line number5 index4 alt2">5</div><div class="line number6 index5 alt1">6</div></td><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="java color1">@CallerSensitive</code></div><div class="line number2 index1 alt1"><code class="java spaces"> </code><code class="java keyword">public</code> <code class="java keyword">static</code> <code class="java plain">Class<?> forName(String className)</code></div><div class="line number3 index2 alt2"><code class="java spaces"> </code><code class="java keyword">throws</code> <code class="java plain">ClassNotFoundException {</code></div><div class="line number4 index3 alt1"><code class="java spaces"> </code><code class="java plain">Class<?> caller = Reflection.getCallerClass();</code></div><div class="line number5 index4 alt2"><code class="java spaces"> </code><code class="java keyword">return</code> <code class="java plain">forName0(className, </code><code class="java keyword">true</code><code class="java plain">, ClassLoader.getClassLoader(caller), caller);</code></div><div class="line number6 index5 alt1"><code class="java spaces"> </code><code class="java plain">}</code></div></div></td></tr></tbody>
java反射中,Class.forName 和 ClassLoader 加载类的区别
原文:https://www.cnblogs.com/chenguihao/p/9509541.html