java Class.forName()和classloader的区别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30788949/article/details/80852560

Class.forName()和classloader都可以对类进行加载,Class.forName()将类加载进jvm的同时还会执行类中的静态static块,而classloader只负责对类进行加载。

我们来看测试代码:

public class A1 {
    static{
        System.out.println("this is A1 static");
    }

    static String ss = getValue();

    public static String getValue(){
        System.out.println("this is A1.getValue");
        return "hhh";
    }

    public static void test(){
        System.out.println("this is A1.test");
    }
}

测试类:

public class Test {

    public static void main(String[] args) throws Exception{
        String A1 = "com.tang.A1";

        testLoader(A1);

        testForName(A1);
    }

    public static void testLoader(String name) throws Exception{
        System.out.println("### begin testLoader");
        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        Class a1 = classLoader.loadClass(name);
        System.out.println("A1.name =  " + a1.getName());

    }

    public static void testForName(String name) throws Exception{
        System.out.println("### begin testForName");
        Class a1 = Class.forName(name);
        System.out.println("A1.name =  " + a1.getName());

    }
}

测试结果:

### begin testLoader
A1.name =  com.tang.A1
### begin testForName
this is A1 static
this is A1.getValue
A1.name =  com.tang.A1
可以看到,classloader只加载类,而Class.forName()加载类的同时还执行了类的static块,还给静态变量赋值,其中静态变量ss的值是通过getValue()得到的,所以也一并执行了。

猜你喜欢

转载自blog.csdn.net/qq_30788949/article/details/80852560