0

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);
Djizeus
  • 4,161
  • 1
  • 24
  • 42
  • Since variables are only used internally, what does it matter if it's called 'myStock' or something specified by the user. Which is to say, what is the use case for this 'feature'? – Roddy of the Frozen Peas Apr 08 '14 at 16:27
  • 1
    possible duplicate of [is there a way to instantiate a class by name in java?](http://stackoverflow.com/questions/9886266/is-there-a-way-to-instantiate-a-class-by-name-in-java) – Djizeus Apr 08 '14 at 16:27
  • @RoddyoftheFrozenPeas I think he meant class instead of object, I edited the question. – Djizeus Apr 08 '14 at 16:28
  • @Dijzeus and yet his code example (somewhat) indicates that the input accepted from the dialog determined the name of the 'Stock' variable. – Roddy of the Frozen Peas Apr 08 '14 at 16:29
  • Hmmm, didn't notice that, maybe I should have asked first... – Djizeus Apr 08 '14 at 16:31

4 Answers4

0

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.

Jere
  • 581
  • 2
  • 3
0

This should do it.

Class.forName(input).newInstance();
Susie
  • 5,038
  • 10
  • 53
  • 74
0

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.

-1

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.

Ctshaw
  • 217
  • 1
  • 5
  • 10