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

后端 未结 3 1737
星月不相逢
星月不相逢 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...

提交回复
热议问题