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

后端 未结 3 1738
星月不相逢
星月不相逢 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:49

    That JavaDoc for Class.getDeclaredConstructor is pretty clear:

    Returns a Constructor object that reflects the specified constructor of the class or interface represented by this Class object. The parameterTypes parameter is an array of Class objects that identify the constructor's formal parameter types, in declared order.

    ... so in your case it's getting a Constructor object that represents a constructor with one argument, which is a String (new Class[] {String.class} constructs a Class[] with a single entry which is the Class object representing java.lang.String). You can call newInstance("some string") on that object in order to invoke the constructor and return a new instance of the target class.

    In practice you probably need to use getConstructor instead of getDeclaredConstructor as the latter will return any constructor that matches the specified parameter types, including ones that would not normally be accessible from outside (e.g. private ones). Conversely, getConstructor will only return public constructors.

提交回复
热议问题