简体   繁体   中英

Java getting name of object reference from the user

How can I ask the user for the name of class and create an object based on the name of the user's class? I know the following code has an error but I hope it gives an idea as what I want to do.

String input = JOptionPane.showInputDialog(null, "Enter the name of object?”); 
Stock input = new Stock(“GOO”,  538);

If you get the name of the class from the user then you first need to attempt to load the class using the static method Class.forName(String name) .

If the classloader can locate the class (meaning it is in the runtime classpath), then you'll get back an instance of the Class object and can invoke the newInstance() method on that.

Note that to do this you must ensure the class has a no-argument constructor, you won't be able to pass arguments to the newInstance() method.

After you have your created instance, you could cast it to a known interface or use reflection to find other methods to call to setup data.

这应该做。

Class.forName(input).newInstance();

You should take a look at reflection .

Anyway, if you allow me to ask such a question, why would you need to do that? I mean reflection is rarely a need, but more of a bad programming pattern that should be used only in precise cases (such as automatically filling an instance using annotations).

Let us know more info about your problem, and maybe we could find a better solution.

What you are doing is creating an object of Stock and naming it the input, as far as I know you cannot create an object based on a string. You can though, if you know what objects you want them to enter, do the following:

String input = JOptionPane.showInputDialog(null, "Enter the name of object?”); 
Switch (input){
case String: String string  = new String();
case int: int Int = new int();

and so on. If this is not the idea of what you wanted to do let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM