如何创建在运行时知道的类的实例? [英] how to create instance of a class to be known at runtime?
本文介绍了如何创建在运行时知道的类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
-
我们如何使用参数化
构造函数创建类的对象,并在
运行时向我们提供类的名称作为命令行参数。
How can we we create an object of a class with parametrized constructor,and the name of the class would be given to us at the run time as command line argument.
这一行意味着什么
new Class [] {String .class}
new Class[]{String.class}
和String.class有什么区别?
and what is the difference between String and String.class ?
推荐答案
1-使用反射在运行时创建类实例:
1- To create a class instance at runtime using reflection :
Class classToInstantiate = Class.forName(className);
Constructor<?> theClassInstructor = classToInstantiate.getDeclaredConstructor(<parametersClasses>);
Object instance = theClassInstructor.newInstance(<parameters>);
使用:
-
parametersClasses
构造函数参数的类数组,例如,如果构造函数使用您编写的String和Integer参数:getDeclaredConstructor(new类[] {String.class,Integer.class});
-
参数
是实际值实例化时使用的参数。
parametersClasses
array of the classes of the constructor parameters, for example if the constructor uses a String and an Integer parameter you write :getDeclaredConstructor(new Class[]{String.class,Integer.class});
parameters
are the actual values of the parameters to use when instantiating.
这篇关于如何创建在运行时知道的类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文