Java反射中Class.forName和classloader的区别

Java中Class.forName和classloader都可以用来对类进行加载。

 

Class.forName除了将类的.class文件加载到jvm中之外,还会对类进行解释,执行类中的static块。

而classloader只干一件事情,就是将.class文件加载到jvm中,不会执行static中的内容,只有在newInstance才会去执行static块。

 

Class.forName(name,initialize,loader)带参数也可控制是否加载static块。并且只有调用了newInstance()方法采用调用构造函数,创建类的对象。

package com.yu.java.reflect;

public class Line {
    static {
        System.out.println("static code executing: loading line...");
    }
}
package com.yu.java.reflect;

public class Point {
    static {
        System.out.println("static code executing: loading point...");
    }
}
package com.yu.java.reflect;

public class ClassLoaderAndForNameTest {

    public static void main(String[] args) {
        String wholeNameLine = "com.mangosoft.java.reflect.Line";
        String wholeNamePoint = "com.mangosoft.java.reflect.Point";

        System.out.println("classloader testing...");
        testClassLoader(wholeNameLine, wholeNamePoint);
        System.out.println("---------------------------------------");
        System.out.println("Class.forName testing...");
        testForName(wholeNameLine, wholeNamePoint);
    }

    //classloader
    public static void testClassLoader(String wholeNameLine, String wholeNamePoint) {
        ClassLoader loader = ClassLoader.getSystemClassLoader();
        Class<?> line;
        Class<?> point;
        try {
            line = loader.loadClass(wholeNameLine);
            point = loader.loadClass(wholeNamePoint);
            System.out.println("line " + line.getName());
            System.out.println("point " + point.getName());
        } catch (ClassNotFoundException e){
            e.printStackTrace();
        }
    }

    //Class.forName
    public static void testForName(String wholeNameLine, String wholeNamePoint) {
        try {
            Class line = Class.forName(wholeNameLine);
            Class point = Class.forName(wholeNamePoint);
            System.out.println("line " + line.getName());
            System.out.println("point " + point.getName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

运行结果如下:

posted @ 2018-08-14 17:55  浅滩沙洲  阅读(1317)  评论(0编辑  收藏  举报