newInstance() 方法

2024 年 8 月 29 日 | 阅读 3 分钟

Class 类和 Constructor 类的 newInstance() 方法用于创建该类的新实例。

Class 类的 newInstance() 方法可以调用无参数构造函数,而 Constructor 类的 newInstance() 方法可以调用任意数量的参数。 因此,Constructor 类优于 Class 类。

Class 类的 newInstance() 方法的语法

public T newInstance()throws InstantiationException,IllegalAccessException

这里 T 是泛型版本。您可以将其视为 Object 类。 您稍后将了解有关泛型的更多信息。

newInstance() 方法示例-1

让我们看一个简单的例子来使用 newInstance() 方法。

文件名: Test.java

输出

Hello java

newInstance() 方法示例-2

在本主题的介绍部分中,我们已经了解到 Class 类的 newInstance() 方法只能调用无参数构造函数。 让我们借助一个例子来理解相同的内容。

文件名: ReflectionExample1.java

输出

/ReflectionExample1.java:15: error: unreported exception InstantiationException; must be caught or declared to be thrown
ob = classDefinition.newInstance();
                                ^
Note: /ReflectionExample1.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 error

说明: Class 类的 newInstance() 方法仅调用零参数构造函数。 但是,我们需要调用非零参数构造函数,为此,我们需要使用 Constructor 类的 newInstance() 方法。

以下程序显示了如何使用 Constructor 类的 newInstance() 方法来避免上述示例中出现的异常。

文件名: ReflectionExample2.java

输出

My JLabel in Reflection.

下一个主题理解 Javap 工具