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 }

 

运行结果如下:

 

转载于:https://www.cnblogs.com/mangosoft/p/6485790.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值