一般情况下,new运算符是用来创建对象的,但是如果我们想在运行时决定要创建的对象的类型,就没有办法使用new运算符了。在这种情况下,我们必须使用 newInstance() 方法。考虑一个例子:
// Java program to demonstrate working of newInstance()
// Sample classes
class A { int a; }
class B { int b; }
public class Test
{
// This method creates an instance of class whose name is
// passed as a string 'c'.
public static void fun(String c) throws InstantiationException,
IllegalAccessException, ClassNotFoundException
{
// Create an object of type 'c'
Object obj = Class.forName(c).newInstance();
// This is to print type of object created
System.out.println("Object created for class:"
+ obj.getClass().getName());
}
// Driver code that calls main()
public static void main(String[] args) throws InstantiationException,
IllegalAccessException, ClassNotFoundException
{
fun("A");
}
}
输出:
Object created for class:A
Class.forName()方法返回类Class对象,我们在该对象上调用newInstance()方法,该方法将返回我们作为命令行参数传递的该类的对象。
如果传递的类不存在,则会发生ClassNotFoundException 。
如果传递的类不包含默认构造函数,则将发生InstantionException,因为newInstance()方法在内部调用该特定类的默认构造函数。
如果我们无权访问指定类定义的定义,则会发生IllegalAccessException 。
相关文章: Java的反射