Java反射 Class.forName 和 loadClass 方法的区别
java中Class.forName()和ClassLoader都可以对类进行加载。ClassLoader就是遵循双亲委派模型最终调用启动类加载器的类加载器,实现的功能是“通过一个类的全限定名来获取描述此类的二进制字节流”,获取到二进制流后放到JVM中。Class.forName()方法实际上也是调用的CLassLoader来实现的。
Class.forName(String className);
用例
Person emp2 = (Person) Class.forName("org.pro.com.Person").newInstance();
源码:
@CallerSensitive public static Class<?> forName(String className) throws ClassNotFoundException { Class<?> caller = Reflection.getCallerClass(); return forName0(className, true, ClassLoader.getClassLoader(caller), caller); }
最后调用的方法是forName0这个方法,在这个forName0方法中的第二个参数被默认设置为了true,这个参数代表是否对加载的类进行初始化,设置为true时会类进行初始化,代表会执行类中的静态代码块,以及对静态变量的赋值等操作。
也可以调用Class.forName(String name, boolean initialize,ClassLoader loader)方法来手动选择在加载类的时候是否要对类进行初始化。Class.forName(String name, boolean initialize,ClassLoader loader)的源码如下:
/* @param name fully qualified name of the desired class * @param initialize if {@code true} the class will be initialized. * See Section 12.4 of <em>The Java Language Specification</em>. * @param loader class loader from which the class must be loaded * @return class object representing the desired class * * @exception LinkageError if the linkage fails * @exception ExceptionInInitializerError if the initialization provoked * by this method fails * @exception ClassNotFoundException if the class cannot be located by * the specified class loader * * @see java.lang.Class#forName(String) * @see java.lang.ClassLoader * @since 1.2 */ @CallerSensitive public static Class<?> forName(String name, boolean initialize, ClassLoader loader) throws ClassNotFoundException { Class<?> caller = null; SecurityManager sm = System.getSecurityManager(); if (sm != null) { // Reflective call to get caller class is only needed if a security manager // is present. Avoid the overhead of making this call otherwise. caller = Reflection.getCallerClass(); if (sun.misc.VM.isSystemDomainLoader(loader)) { ClassLoader ccl = ClassLoader.getClassLoader(caller); if (!sun.misc.VM.isSystemDomainLoader(ccl)) { sm.checkPermission( SecurityConstants.GET_CLASSLOADER_PERMISSION); } } } return forName0(name, initialize, loader, caller); }
源码中的注释只摘取了一部分,其中对参数initialize的描述是:if {@code true} the class will be initialized.意思就是说:如果参数为true,则加载的类将会被初始化
class.loadClass
用例
ClassLoader cl; // 如何获得ClassLoader参考1.6
Class cls = cl.loadClass("com.rain.B"); // 使用第一步得到的ClassLoader来载入B
B b = (B)cls.newInstance(); // 有B的类得到一个B的实例
ClassLoader.loadClass()源码
public Class<?> loadClass(String name) throws ClassNotFoundException { return loadClass(name, false); } ... ... /** * @param resolve * If <tt>true</tt> then resolve the class */ protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // First, check if the class has already been loaded Class<?> c = findLoadedClass(name); if (c == null) { try { if (parent != null) { c = parent.loadClass(name, false); } else { c = findBootstrapClassOrNull(name); } } catch (ClassNotFoundException e) { // ClassNotFoundException thrown if class not found // from the non-null parent class loader } if (c == null) { // If still not found, then invoke findClass in order // to find the class. c = findClass(name); } } return c; }
loadClass(String name)方法调用了loadClass(String name, boolean resolve),resolve为false,即为通过ClassLoader.loadClass加载的类不进行解析操作,不进行解析操作就意味着初始化也不会进行,那么其类的静态参数就不会初始化,静态代码块也不会被执行。
再来看看代码:
测试对比打印调用静态代码用例
测试类
public class TestBean {
public static String param1 = "testBean";
static {
System.out.println("====TestBean====");
}
}
使用Class.forName(String className);
try {
Class.forName("com.jm.loaderTest.TestBean");
System.out.println("#########-------------结束符------------##########");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
打印结果,打印了静态代码
使用 ClassLoader.loadClass()源码
try {
ClassLoader.getSystemClassLoader().loadClass("com.jm.loaderTest.TestBean");
System.out.println("#########-------------结束符------------##########");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
打印结果,没有打印静态代码
可以看到 forName 执行静态代码, loadClass 没有
-------------------------------------------------------------------------------------------------------------------------------------
【1】https://www.cnblogs.com/jimoer/p/9185662.html
【2】https://blog.csdn.net/zhangshuny/article/details/106898286
Class.forName 和 .loadClass 方法的区别
原文:https://www.cnblogs.com/Jomini/p/13749568.html