Class.forName与ClassLoader.loadClass的区别
来源:互联网 发布:淘宝助手怎么用 编辑:程序博客网 时间:2024/05/01 20:14
类名.classJava中每个被加载的类,在jvm中都会有一个Class对象与之相对应,类名.class是Class对象的句柄,如果要创建新的对象,直接使用Class对象的方法Class.forName()就可以了,不需要用new类名。在Java中,每个class都有一个相应的Class对象,当编写好一个类,编译完成后,在生成的.class文件中,就产生一个class对象,用来表示这个类的类型信息。获得Class实例的三中方式: 利用对象调用getClass()方法获取该对象的Class实例 使用Class的静态方法forName(),用类的名字获取一个Class实例 运用.calss的方式获取Class实例,对基本数据类型的封装类,还可以采用.TYPE来获取对应的基本数据类型的Class实例package org.zeroup; /** * 研究Class.forName与ClassLoader.loadClass()区别 * * @author Andy * */public class ClassForNameAndClassLoaderTest { public static void main(String[] args) { // 利用对象调用getClass()方法获取该对象的Class实例 Point pt = new Point(); Class c1 = pt.getClass(); System.out.println(c1.getName()); // 结果:org.zeroup.Point // 使用Class的静态方法forName(),用类的名字获取一个Class实例 try { Class c2 = Class.forName("org.zeroup.Point"); System.out.println(c2.getName()); // 结果:Point } catch (Exception e) { e.printStackTrace(); } // 运用.calss的方式获取Class实例(类) Class c3 = Point.class; System.out.println(c3.getName()); // 结果:org.zeroup.Point // 运用.calss的方式获取Class实例(基本类型) Class c4 = int.class; System.out.println(c4.getName()); // 结果:int // 运用.calss的方式获取Class实例(基本数据类型的封装类) Class c5 = Integer.TYPE; System.out.println(c5.getName()); // 结果:int Class c6 = Integer.class; System.out.println(c6.getName()); // 结果:java.lang.Integer // 以下结果是: before new Point() loading point after new Point() loading // Line // 当new Point()的时候加载这个类,用forName构造实例的时候也加载该类。 System.out.println("before new Point()"); new Point(); System.out.println("after new Point()"); try { Class.forName("org.zeroup.Line"); } catch (Exception e) { e.printStackTrace(); } }} class Point { static { System.out.println("loading point"); } int x, y;} class Line { static { System.out.println("loading Line"); }}