一般来说,new操作符用于创建对象,但如果我们想在运行时确定要创建的对象的类型,就无法使用new操作符。在这种情况下,我们必须使用newInstance()方法。考虑一个例子:
null
// 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
班forName() 方法返回类 班 我们呼叫的对象 newInstance() 方法,它将返回我们作为命令行参数传递的类的对象。 如果通过的类不存在,那么 ClassNotFoundException 将会发生。 InstanceException 如果传递的类不包含默认构造函数 newInstance() 方法在内部调用该特定类的默认构造函数。 非法访问例外 如果我们无法访问指定类定义的定义,将发生。
相关文章: Java中的反射
本文由 高拉夫·米格拉尼 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END