0

I have some String variables:

private String cur, last, avg, vol, shop;

I have method which accept String and gives me some result:

public void SomeMethod(String somestring)
{
    //Here some action with `string`
    System.out.print(result)
}

So i want to put result into one of String variables, but this variable must be named as value of somestring in my method. Some method which compare somestring with existent variables names. Is such a thing even possible?

5
  • Via Reflection, it's possible :) Commented Jan 27, 2014 at 9:49
  • 2
    Probably with reflection you can do it, but it's really a bad solution to me... What are you trying to accomplish? Why should you change variable names according to their contents? Commented Jan 27, 2014 at 9:49
  • I don't want change variable names. I just want compare name of variable and value of somestring and set value of that variable as result. Commented Jan 27, 2014 at 9:51
  • This is not probably what you want. As a var's name will never be relevant to your program's usage in runtime (unless you're making a debugging tool or a compiler or something, are you ?). Commented Jan 27, 2014 at 9:51
  • Nope. But it's what i want. Commented Jan 27, 2014 at 9:54

1 Answer 1

1

You're talking about variable variable name. They're a native feature in PHP, but not in Java, however you can achieve similar functionality using a HashMap, or using Reflection. I'm going to show you the HashMap option, because frankly Reflection is the work of Satan.

Example

Now the way to implement this is like this:

public void someMethod(String name, String value)
{
    values.put(name, value);
}

And you can retrieve them with

public void getValue(String name)
{
    return values.get(name);
}

I won't write the code for you, because it's a simple transformation to get this to work in your use case.

A hint because I'm feeling nice

You can replace all of your String variables with a Map implementation. Then simply add the values to the Map, as and when the need arises.

Sign up to request clarification or add additional context in comments.

3 Comments

I thought there is maybe a way to get variable names and compare, but some kind of array is working too. Thanks.
There is, Reflection, but by using Reflection, you achieve the exact same functionality in a much, much less efficient way. And this isn't an array. It's a Map.
Ok. Not array, but collection?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.