java 用new创建实例_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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值