Reputation: 695
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?
Upvotes: 0
Views: 124
Reputation: 27356
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.
Upvotes: 1