简体   繁体   English

实例之间的差异

[英]Differences between instances

been messing around with JFrames a bit, and I noticed something: 与JFrames有点混乱,我注意到了一些东西:

JFrame frame = new JFrame();

Works, from what I can tell, the exact same as: 据我所知,它的工作原理完全相同:

JFrame frame = JFrame.class.newInstance();

Are there any differences between these two ways when just using the Default instance with no parameters? 仅使用不带参数的Default实例时,这两种方式之间有什么区别吗?

Thanks, 谢谢,

Legend 传说

The newInstance() method in java.lang.Class constructs an instance of the class using the no-argument contructor -- so no, the two JFrame s would be identical. java.lang.ClassnewInstance()方法使用无参数构造函数构造该类的实例-因此,这两个JFrame是相同的。

The Class.newInstance() method becomes important when the Class object is created using a class name at runtime -- for example, a class name read from a file. 当在运行时使用类名创建Class对象时, Class.newInstance()方法变得很重要-例如,从文件中读取的类名。 Then you can say 那你可以说

String theClassName = ...;
Class clazz = Class.forName(theClassName);
Object o = clazz.newInstance();

Now you have an instance of a class whose name was not known when this code was compiled. 现在,您有了一个类的实例,该类的名称在编译此代码时不知道。 If you know (by convention) that the named class implements some interface or extends some class, then you can cast the Object to that interface or class, and use it that way. 如果(按照惯例)知道命名的类实现了某个接口或扩展了某个类,则可以将Object转换为该接口或类,然后以这种方式使用它。 This is how, for example, servlet containers load servlets as described in configuration files, or web browsers load applets named in HTML. 例如,这就是servlet容器如何按配置文件中的描述加载servlet或Web浏览器加载以HTML命名的applet的方式。

newInstance() throws two checked exceptions that you have to deal with, and it prevents the compiler from telling you when you're doing something wrong (like trying to instantiate an abstract class). newInstance()引发两个必须处理的检查异常,它防止编译器在做错事情时告诉您(例如尝试实例化抽象类)。

And there's no such thing as a "Default instance." 而且没有“默认实例”之类的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM