使用传统的Class c = new Class();和使用Class.forName("class").newInstance();哪个更好,效率更高呢?请指教,谢谢.

解决方案 »

  1.   

    new的效率稍微高一些,但没有太大区别如果能直接new,为什么要用反射来做?!况且,对于有参数的构造方法的类来说,反射更麻烦
      

  2.   

    能用new,就不要用反射。
      

  3.   

    You lose all the benefits of compile-time type checking, including exception
    checking. If a program attempts to invoke a nonexistent or inaccessible method
    reflectively, it will fail at runtime unless you’ve taken special precautions.
    • The code required to perform reflective access is clumsy and verbose. It is
    tedious to write and difficult to read.
    • Performance suffers. Reflective method invocation is much slower than
    normal method invocation. Exactly how much slower is hard to say, because
    there are so many factors at work. On my machine, the speed difference can be
    as small as a factor of two or as large as a factor of fifty.effective java 2nd edition,Item 53: Prefer interfaces to reflection
      

  4.   

    应该new效率高,可以通过反编译查看生成的指令代码
    后一种方法会多出一些步骤,比如查找类,生成实例后还要进行类型检查(newInstance返回的是个Object,虽然有了泛型,但实际内部处理还是Object)
    所以在既知类型的前提下,new要好,没必要走弯路,Class.forName()还有可能出异常
    除非是动态生成实例,也就是说对于一些面向接口的编程,根据不同的业务参数去动态生成接口的具体实现的实例时,new就不能很好的胜任了
      

  5.   

    非要说的话是用反射好一些,这样做耦合就低了,你可以把要实例化的类名放到配置文件里,需要的时候创建实例,这样你要是想实例化其他类,在配置文件里改一下就行了。开发中一般这么做,不过平时学习的话还是直接new()出来,因为反射太麻烦。