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

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

    Class c = Class.forName(args[0]);

    This gets a Class<?> object...

    Constructor ctr = c.getDeclaredConstructor(new Class[]{String.class})

    and this gets a constructor for that class which argument is a single String.

    Once you have that you can invoke ctr.newInstance(someString).

    You have a problem though, in that you don't really know the class here. You should at least have an idea of a common subtype, otherwise all you'll ever get is an Object...

    0 讨论(0)
  • 2021-01-25 10:44

    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>);
    

    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.
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题