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

后端 未结 6 740
时光说笑
时光说笑 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: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.

提交回复
热议问题