-1

I would like to call an object through the use of a generated string.

As you can see, name is being generated correctly. Also, the method for getting the object works fine. However I can not use name to reference the object even though that is the name of the object.

Why is that? How can I solve this?

public class FrameTest{    
    public static void main(String[] args) { 
        ObjectMethod first_object = new ObjectMethod(); //instanciate object
        first_object.setCost(2.5);

        String object = "first";
        String one = "object";
        String name = object + "_" + one;

        System.out.println(name);
        System.out.println(first_object.getCost());
        System.out.println(name.getCost()); //this line does not work
    }
}

public class ObjectMethod{
    public double value;

    public void setCost(double cost) {
        value = cost;
    }

    public double getCost() {
        return value;
    }
}
Jon Goe
  • 165
  • 2
  • 13
  • I think you need to say what you're trying to achieve. It looks as if you are trying to do something which should be done a different way. We may be able to help if you say what the task is – Richard May 05 '17 at 10:38
  • 1
    Is [this](http://stackoverflow.com/questions/160970/how-do-i-invoke-a-java-method-when-given-the-method-name-as-a-string) what you are looking for? – Courage May 05 '17 at 10:40
  • I have in the past and people have told me to shorten and narrow my question. Basically, I have two combo boxes, a and b. Both combo boxes contains 1 and 2. I have created two objects. 1_2 and 2_1. I am trying to make it so that based on the value selected in the combo box, a specific object will be refered to. My solution to this was to create the objects with the values of the combo boxes joined by _. I could then refer to these objects based on the value selected value of the combo boxes. Im not sure this made sense, hopefily I could make myself clear. – Jon Goe May 05 '17 at 10:43
  • @JonGoe if there are just 2 objects in the combo, why dont you just use an if/else statement? – Courage May 05 '17 at 10:47
  • 1
    op wants ([in](http://stackoverflow.com/questions/43782354/java-using-object-from-class-in-another-class) many opportunities )to call a method from ObjectMethod in a string class... all questions pointing to the same: http://stackoverflow.com/a/43784461/982161 – ΦXocę 웃 Пepeúpa ツ May 05 '17 at 10:52
  • @Oswald There are 25 objects. – Jon Goe May 05 '17 at 11:04

5 Answers5

2

You have to understand: Java isn't ruby or python or some other dynamic language.

There is no magic connection that allows you to turn a reference to a String into something else.

In other words: the fact that you put "object_one" into a string object doesn't allow you to treat that String like some actual variable object_one.

The one feature of Java that goes into that direction is reflection. But that is really an advanced topic; and before you look into that, you should understand the real basics of Java. So, better start here.

What I mean is: as the answer by "slim" points out: you could use a Map in order to implement some sort of "call by name" functionality. But the point is: that is "not how you do things in Java". Java is a statically compiled language; and there is no sense in using Java when one then tries to break out of that system and do things that rely on flat string parsing at runtime.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
2

The closest I can think of to what you're describing, short of using Reflection (if you're asking this question, you're not ready for Reflection) is to have a map of strings to objects.

  Map<String,Runnable> options = new HashMap<>();
  options.add("getCost", new CostGetter(...));
  options.add("getDescription", new DescriptionGetter(...));

  String command = getCommandFromUi();
  options.get(command).run();

It could be Callable rather than Runnable. It could be an interface of your own. In Java 8 it could be Supplier and you could pass lambdas:

  options.add("getCost", () -> currentUser.price());

Have a look at the Command and Strategy patterns in any book about design patterns.

slim
  • 40,215
  • 13
  • 94
  • 127
  • Thats a good point; you got my vote for that. Although I still think that the OP is rather going down the wrong rabbit hole. He should understand the statically typed nature of Java; instead of trying to use Java in dynamic-scripting-language mental model. But as said; you got my vote here ;-) – GhostCat May 05 '17 at 11:10
  • @GhostCat Understood. I made 25 if statements each calling the different objects based on the different values of the combo boxes. I will look for something better but for now it works. Thanks – Jon Goe May 05 '17 at 12:31
1

This will not work as you wish, because you are trying to call getCost() on String name object. name - is just a string, but not the object of ObjectMethod class.

0

You cannot invoke name.getCost() and type of name is String, and string donot have getCost() method. Hence, your code fails here.

String name = object + "_" + one;

In above code, you are assigning name field with value "object_first". That means, field name is type of String with value "object_first". So, name is in no way related to ObjectMethod class, and hence name.getCost() make no sense.

Basically, what you are trying to accomplish

"I would like to call an object through the use of a generated string"

is not possible unless you use reflection.

Ra Ka
  • 2,995
  • 3
  • 23
  • 31
0

java is a Strong typed language that means you have to define a variable and also specify the variable type before you use it and (emphasis mine) Certain operations may be allowable only to that type*

just because you do:

String objectName;
Object comboValue  = departingStop.getSelectedItem();
Object combo2Value = finalStop.getSelectedItem();
objectName = comboValue + "_" + combo2Value;

dosn't mean that now objectName mutated from string into a ComboBox...

imagine how terrible this could be:

Car tata = new Car();
Robot kuka = new Robot();
String foo = tata.getName() + kuka.getName();

now what is foo? a transformer?? NO, is still a String... since that is a string you just can not do foo.drive(), because is not a car, neither foo.weld(); because is not a robot

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97