Can I Instantiate a class using the class object? What about Constructors?

后端 未结 6 741
时光说笑
时光说笑 2020-12-09 18:15

I am storing a list of classes through (Classname.class) and would like to instantiate one? Is this possible?

newInstance seems to the met

相关标签:
6条回答
  • 2020-12-09 18:42

    You can use Class.getConstructors (or Class.getConstructor) to get a list of available constructors, and invoke any of them with Constructor.newInstance, which does accept parameters.

    0 讨论(0)
  • 2020-12-09 18:46

    Just to add one point I see missing:

    You can invoke newInstance directly on the Class object if it has a public null constructor. (Null constructor is the constructor with no arguments.)

    Otherwise, you can find constructors via Class.getConstructors() as others have said.

    0 讨论(0)
  • 2020-12-09 18:53

    The Java tutorial on reflection covers this well. But yeah, basically Class.getConstructors, then Constructor.newInstance is where it's at.

    0 讨论(0)
  • 2020-12-09 18:54

    Java is designed so you can never "trick" it as long as you use the java.lang/java. classes or other standard libraries. One of the most important things of OOP is that objects should be in a defined state, thus you can be safe that the constructor is always run. Even if you're using some strange-looking reflection libraries to get your work done.

    So, using Class.forName("me.Test").newInstance(); (or similar) will under-the-hood invoke the Test() constructor for you.

    If you want to invoke another constructor the code is something like:

    Test test = (Test)Class.forName("Test").getConstructor(String.class).newInstance("Hello World");
    

    Here the getConstructor asks what the constructor looks like (it wants a string) and then you call it with a string.

    0 讨论(0)
  • 2020-12-09 18:55

    You cannot construct new classes this way.

    If you have the name of a class you can use Class.forName(className) to load/reference a class.

    If you have the byte code for a class you want to create you can have a class loader load the byte code and give you the class. This is likely to be more advanced than you intended.

    0 讨论(0)
  • 2020-12-09 19:01

    If you have a list of Class objects obtained through class literals, you might as well statically reference the constructors rather than slipping into reflection evilness.

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