how to create instance of a class to be known at runtime?

后端 未结 3 1770
星月不相逢
星月不相逢 2021-01-25 10:25
  1. 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.

3条回答
  •  长发绾君心
    2021-01-25 10:44

    1- To create a class instance at runtime using reflection :

    Class classToInstantiate = Class.forName(className);
    Constructor theClassInstructor = classToInstantiate.getDeclaredConstructor();
    Object instance = theClassInstructor.newInstance();
    

    With:

    • 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.

提交回复
热议问题