java 反射创建实例与new创建实例的区别

new创建实例

new创建一个编译时已知的类的实例,也即是静态的创建实例;

可以调用类的任何构造器来创建实例;

速度更快,由于可以将需要的类写入字节文件中(hardcoded into the bytecode)。

反射创建实例(如Class.forName().newInstance())

反射创建实例是动态的创建一个类的实例;

只能调用类的无参数构造器来创建实例;

速度较慢。

 为什么需要Class.forName("your class name").newInstance()创建实例

例如需要从远端动态地加载类,只知道这些类的名字,是无法使用import将其导入程序中的,这个时候可以利用反射创建实例

(以上内容整理自StackOverFlow)

The new operator creates a new object of a type that's known statically (at compile-time) and can call any constructor on the object you're trying to create. It's the preferred way of creating an object - it's fast and the JVM does lots of aggressive optimizations on it.

Class.forName().newInstance() is a dynamic construct that looks up a class with a specific name. It's slower than using new because the type of object can't be hardcoded into the bytecode, and because the JVM might have to do permissions checking to ensure that you have the authority to create an object. It's also partially unsafe because it always uses a zero-argument constructor, and if the object you're trying to create doesn't have a nullary constructor it throws an exception.

In short, use new if you know at compile-time what the type of the object is that you want to create. Use Class.forName().newInstance() if you don't know what type of object you'll be making.

Class.forName("your class name").newInstance() is useful if you need to instantiate classes dynamically, because you don't have to hard code the class name to create an object.

Imagine a scenario where you load classes dynamically from a remote source. You will know their names but can't import them at compile time. In this case you can't use new to create new instances. That's (one reason) why Java offers the newInstance() method.

Class.forName("your class name").newInstance() is used when you want to get an instance form a class work similar to new, but it is useful when you want to get instance from a class in a jar file or remote server and you can not import it in compile time.

ex: Class.forName("YOUR JDBC DRIVER").newInstance(), you can not import the JDBC class at compile time.

原文地址:https://www.cnblogs.com/deltadeblog/p/9392302.html