0

Let's say I have a

public class things {
    String name = new string;
    int nr = new nr;
    //constructor etc
}

Now let's assume there are already a bunch of instances initialized. let's call them thingA, thingB, thingC (I will need them to be more later...)

I'm having a JFrame where the User can Input a text and the input shall be one of the classes so he could type "thingB", "thingD", ... "thingN"

within an actionPerformed I now want to:

String s = jLabel_1.getText();

and then do sth like.

System.out.println("" + s.nr)

Obviously, that doesn't work since s is a string only containing the value entered in the text-label, so what I wanna do is tell Java that the object's name I'm trying to use is the one saved in 's'. I really tried to look it up but I couldn't find anything except a

Class.forName(String...) option which didn't really work either, respectively I didn't know how to use it.

9
  • have you tried this step by step? stackoverflow.com/questions/4030618/java-string-to-class Commented Feb 26, 2018 at 10:19
  • Class.forName(label.getText()) should work if the user enters the full class name. If they don't, you need to concatenate their input with the package name where these classes are located Commented Feb 26, 2018 at 10:23
  • That is just supposed to get the class, but not the instance. OP says he wants to get the instance from a set of those inputting a string with the name of the variable they're stored in. To be honest it sounds complicated but all he would have to do is create a String in the class with the name of the variable, and store all the instances in an array, then compare the input with the String of the instances and the rest is easy. Commented Feb 26, 2018 at 10:32
  • There might be a way to get the object itself from the name. But, here is a simple approach that I know. Store all the instances in a list. From the string input that you have got, Use JAVA reflection and compare each of those instance's name from the list. Commented Feb 26, 2018 at 10:32
  • "There might be a way to get the object itself from the name. But, here is a simple approach that I know. Store all the instances in a list. From the string input that you have got, Use JAVA reflection and compare each of those instance's name from the list." --> This sounds pretty good, will try that! Thanks for your comments so far, if anyone has an idea on how to do it directly I'm more than open :) Commented Feb 26, 2018 at 10:41

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.