通常,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()方法返回类我们在其上调用newInstance()方法的对象,它将返回我们作为命令行参数传递的该类的对象。 如果传递的类不存在则会发生ClassNotFoundException。如果传递的类不包含默认构造函数,则会发生InstantionException,因为newInstance()方法在内部调用该特定类的默认构造函数。如果我们无法访问指定类定义的定义,则会发生IllegalAccessException

 
转载请保留页面地址:https://www.breakyizhan.com/java/5009.html
扫描二维码添加微信 
  • ,每次淘宝领取淘宝优惠券,淘宝购物更优惠。现在添加微信,还可以领取机械键盘50元优惠券!添加微信后回复机械键盘即可领取!
    支持我们,就用微信淘宝!