new运算符和Class.newInstance()有什么区别? [英] What is the difference between the new operator and Class.newInstance()?

查看:583
本文介绍了new运算符和Class.newInstance()有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

new 运算符与 Class.forName(...)。newInstance()之间有什么区别?它们都创建了一个类的实例,我不确定它们之间的区别。

What is the difference between new operator and Class.forName(...).newInstance()? Both of them create instances of a class, and I'm not sure what the difference is between them.

推荐答案

new 运算符创建一个静态已知类型的新对象(在编译时),并且可以调用您尝试创建的对象上的任何构造函数。这是创建对象的首选方式 - 它很快,JVM对它进行了大量的积极优化。

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 ()是一个动态构造,用于查找具有特定名称的类。它比使用 new 慢,因为对象的类型不能硬编码到字节码中,并且因为JVM可能必须进行权限检查以确保您有权使用创建一个对象。它也部分不安全,因为它总是使用零参数构造函数,如果你想要创建的对象没有一个无效的构造函数,它会抛出异常。

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.

简而言之,如果您在编译时知道要创建的对象类型,请使用 new 。如果你不知道你要做什么类型的对象,请使用 Class.forName()。newInstance()

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.

这篇关于new运算符和Class.newInstance()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆