Java教程-newInstance()方法

newInstance()方法
Class类和Constructor类的newInstance()方法用于创建类的新实例。
Class类的newInstance()方法可以调用无参构造函数,而Constructor类的newInstance()方法可以调用任意数量的参数。因此,优先使用Constructor类而不是Class类。
Class类的newInstance()方法的语法
public T newInstance() throws
InstantiationException,IllegalAccessException
这里的T是泛型版本。您可以将其视为Object类。您将在后面学习有关泛型的知识。
newInstance()方法示例-1
让我们看一个使用newInstance()方法的简单示例。
文件名:Test.java
class Simple{
void message(){System.out.println("Hello Java");}
}
class Test{
public static void main(String args[]){
try{
Class c=Class.forName("Simple");
Simple s=(Simple)c.newInstance();
s.message();
}catch(Exception e){System.out.println(e);}
}
}
输出:
Hello java
newInstance()方法示例-2
我们在本主题的介绍部分中学到了Class类的newInstance()方法只能调用无参构造函数。让我们通过一个例子来理解。
文件名:ReflectionExample1.java
// 重要的导入语句
import static java.lang.System.out;
import java.lang.reflect.*;
import javax.swing.*;
public class ReflectionExample1
{
// 允许 Java 虚拟机处理 ClassNotFoundException
// 主要方法
public static void main(String argvs[]) throws ClassNotFoundException
{
Object ob = null;
Class classDefinition = Class.forName("javax.swing.JLabel");
ob = classDefinition.newInstance();
// 用于保存类实例的实例变量
JLabel l1;
// 检查创建的对象ob是否是
// 是否为 JLabel 的实例。
// 如果是,则进行类型转换;否则,终止该方法
if(ob instanceof JLabel)
{
l1 = (JLabel)ob;
}
else
{
return;
}
// 到达这里意味着类型转换已经完成
// 现在我们可以调用 getText() 方法
out.println(l1.getText());
}
}
输出:
/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
// 重要的导入语句
import static java.lang.System.out;
import java.lang.reflect.*;
import javax.swing.*;
public class ReflectionExample2
{
// 主要方法
public static void main(String argvs[])
{
try
{
Class[] t = { String.class };
Class classDef = Class.forName("javax.swing.JLabel");
// 获取构造函数
Constructor cons = classDef.getConstructor(t);
// 设置标签
Object[] objct = { "My JLabel in Reflection."};
// 这次通过调用正确的构造函数来获取实例
Object ob = cons.newInstance(objct);
// 用于保存类实例的实例变量
JLabel l1;
// 检查创建的对象ob是否是
// 是否为 JLabel 的实例。
// 如果是,则进行类型转换;否则,退出该方法
if(ob instanceof JLabel)
{
l1 = (JLabel)ob;
}
else
{
// 使用 return 语句退出方法
}
// 如果控件到达这里,则意味着类型转换已经完成
// 现在我们可以打印 JLabel 实例的标签
out.println(l1.getText());
}
// 用于处理引发的异常的相关 catch 块。
catch (InstantiationException ie)
{
out.println(ie);
}
catch (IllegalAccessException ie)
{
System.out.println(ie);
}
catch (InvocationTargetException ie)
{
out.println(ie);
}
catch (ClassNotFoundException e)
{
out.println(e);
}
catch (NoSuchMethodException e)
{
out.println(e);
}
}
}
输出:
My JLabel in Reflection.