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()方法采用调用构造函数,创建类的对象。

 

代码如下:

 1 package com.mangosoft.java.reflect;
 2 
 3 /**
 4  * Created by zhangshengjian on 2017/3/1.
 5  */
 6 public class Line {
 7     static {
 8         System.out.println("static code executing: loading line...");
 9     }
10 }
 1 package com.mangosoft.java.reflect;
 2 
 3 /**
 4  * Created by zhangshengjian on 2017/3/1.
 5  */
 6 public class Point {
 7     static {
 8         System.out.println("static code executing: loading point...");
 9     }
10 }
 1 package com.mangosoft.java.reflect;
 2 
 3 /**
 4  * classloader和Class.forName的区别
 5  *
 6  * Created by zhangshengjian on 2017/3/1.
 7  */
 8 public class ClassLoaderAndForNameTest {
 9 
10     public static void main(String[] args) {
11         String wholeNameLine = "com.mangosoft.java.reflect.Line";
12         String wholeNamePoint = "com.mangosoft.java.reflect.Point";
13 
14         System.out.println("classloader testing...");
15         testClassLoader(wholeNameLine, wholeNamePoint);
16         System.out.println("---------------------------------------");
17         System.out.println("Class.forName testing...");
18         testForName(wholeNameLine, wholeNamePoint);
19     }
20 
21     //classloader
22     public static void testClassLoader(String wholeNameLine, String wholeNamePoint) {
23         ClassLoader loader = ClassLoader.getSystemClassLoader();
24         Class<?> line;
25         Class<?> point;
26         try {
27             line = loader.loadClass(wholeNameLine);
28             point = loader.loadClass(wholeNamePoint);
29             System.out.println("line " + line.getName());
30             System.out.println("point " + point.getName());
31         } catch (ClassNotFoundException e){
32             e.printStackTrace();
33         }
35     }
36 
37     //Class.forName
38     public static void testForName(String wholeNameLine, String wholeNamePoint) {
39         try {
40             Class line = Class.forName(wholeNameLine);
41             Class point = Class.forName(wholeNamePoint);
42             System.out.println("line " + line.getName());
43             System.out.println("point " + point.getName());
44         } catch (ClassNotFoundException e) {
45             e.printStackTrace();
46         }
47     }
48 }

 

运行结果如下:

 

posted @ 2017-03-01 19:11  坚持到放弃  阅读(6518)  评论(2编辑  收藏  举报