Java – how to instantiate an object using its string

In Java, suppose I have a string variable:

String x = "CoolClass";

I have a class called coolclass that has a working constructor How to create a coolclass object using variable x instead of typing coolclass itself

(I need to do this because x will be given by the user and read in by scanner, and different objects / classes will be constructed accordingly according to their input)

Solution

Class.forName(x).newInstance()
Class.forName(x).newInstance()

While reflection can be tricky and dangerous, it can be effective Can you tell us what you really want to do?

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>