Java中class.forName和classLoader加载类的区分

Java中class.forName和classLoader都可用来对类进行加载。前者除了将类的.class文件加载到jvm中之外,还会对类进行解释,执行类中的static块。而classLoader只干一件事情,就是将.class文件加载到jvm中,不会执行static中的内容,只有在newInstance才会去执行static块。Class.forName(name, initialize, loader)带参函数也可控制是否加载static块。并且只有调用了newInstance()方法采用调用构造函数,创建类的对象 示例代码如下: 

package com.blueray.java.test;
 
public class ClassLoaderTest {
 
    /**
    * @param args
    */
    public static void main(String[] args) {
        ClassLoader classLoader=StaticSample.class.getClassLoader();
        try {
            System.out.println("Before load class");
            Class clazz=classLoader.loadClass(StaticSample.class.getName());
            System.out.println("After load class.");
            System.out.println("executing newInstance");
            clazz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 
}

StaticSample:

package com.blueray.java.test;
 
public class StaticSample {
    static{
        System.out.println(StaticSample.class.getName()+" is loading the static block");
    }
    public StaticSample(){
        System.out.println("StaticSample Constructor is executing.");
    }
   
   
}

运行结果如下:

Before load class
After load class.
executing newInstance
com.blueray.java.test.StaticSample is loading the static block
StaticSample Constructor is executing.

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/f11deb1ad667e78eb01d564594142969.html