new Instance()方法和new 关键字的区别

来源:互联网 发布:tv是哪个国家的域名 编辑:程序博客网 时间:2024/04/30 00:01
在初始化一个类,生成一个实例的时候,newInstance()方法和new关键字除了一个是方法,一个是关键字外,最主要有什么区别?它们的区别在于创建对象的方式不一样,前者是使用类加载机制,后者是创建一个新类。那么为什么会有两种创建对象方式?这主要考虑到软件的可伸缩、可扩展和可重用等软件设计思想。 Java中工厂模式经常使用newInstance()方法来创建对象,因此从为什么要使用工厂模式上可以找到具体答案。 例如: class c = Class.forName(“Example”); factory = (ExampleInterface)c.newInstance(); 其中ExampleInterface是Example的接口,可以写成如下形式: String className = "Example"; class c = Class.forName(className); factory = (ExampleInterface)c.newInstance(); 进一步可以写成如下形式: String className = readfromXMlConfig;//从xml 配置文件中获得字符串 class c = Class.forName(className); factory = (ExampleInterface)c.newInstance(); 上面代码已经不存在Example的类名称,它的优点是,无论Example类怎么变化,上述代码不变,甚至可以更换Example的兄弟类Example2 , Example3 , Example4……,只要他们继承ExampleInterface就可以。 从JVM的角度看,我们使用关键字new创建一个类的时候,这个类可以没有被加载。但是使用newInstance()方法的时候,就必须保证:1、这个类已经加载;2、这个类已经连接了。而完成上面两个步骤的正是Class的静态方法forName()所完成的,这个静态方法调用了启动类加载器,即加载java API的那个加载器。 现在可以看出,newInstance()实际上是把new这个方式分解为两步,即首先调用Class加载方法加载某个类,然后实例化。 这样分步的好处是显而易见的。我们可以在调用class的静态加载方法forName时获得更好的灵活性,提供给了一种降耦的手段。 最后用最简单的描述来区分new关键字和newInstance()方法的区别: newInstance: 弱类型。低效率。只能调用无参构造。 new: 强类型。相对高效。能调用任何public构造。Class aClass = Class.forName(xxx.xx.xx);Object anInstance = aClass.newInstance();Class.forName("").newInstance()返回的是objectbut there is some limit for this method to create instancethat is your class constructor should no contain parameters, and you should cast the instance manually.Class Driver{protected static Driver current;public static Driver getDriver(){return current;}}Class MyDriver extends Driver{static{Driver.current=new MyDriver();}MyDriver(){}}用时:Class.forName("MyDriver");Driver d=Driver.getDriver();有的jdbc连接数据库的写法里是Class.forName(xxx.xx.xx);而有一些:Class.forName(xxx.xx.xx).newInstance(),为什么会有这两种写法呢?Class.forName(xxx.xx.xx) 返回的是一个类,.newInstance() 后才创建一个对象Class.forName(xxx.xx.xx);的作用是要求JVM查找并加载指定的类,也就是说JVM会执行该类的静态代码段在JDBC规范中明确要求这个Driver类必须向DriverManager注册自己,即任何一个JDBC Driver的Driver类的代码都必须类似如下:public class MyJDBCDriver implements Driver {static {DriverManager.registerDriver(new MyJDBCDriver());}}所以我们在使用JDBC时只需要Class.forName(XXX.XXX);就可以了we just want to load the driver to jvm only, but not need to user the instance of driver, so call Class.forName(xxx.xx.xx) is enough, if you call Class.forName(xxx.xx.xx).newInstance(), the result will same as calling Class.forName(xxx.xx.xx), because Class.forName(xxx.xx.xx).newInstance() will load driver first, and then create instance, but the instacne you will never use in usual, so you need not to create it.在JDBC驱动中,有一块静态代码,也叫静态初始化块,它执行的时间是当class调入到内存中就执行(你可以想像成,当类调用到内存后就执行一个方法)。所以很多人把jdbc driver调入到内存中,再实例化对象是没有意义的。资源引用:http://hi.baidu.com/wangyuege/blog/item/3e9fd8a2cc4e16accbefd080.html