Creating a Variable Name Using a String Value

Creating a variable name using a String value

While you can do what you're trying in some scripting languages such as PHP (and this question is often asked by many PHP programmers who start Java), this is not how Java works, and in fact variable names are a much less important than you may realize and hardly even exist after code is compiled. What is much more important and what is key are variable references -- the ability to gain access to a particular object at a particular point in your program, and you can have Strings refer to objects easily by using a Map as one way.

For example

Map<String, Dog> dogMap = new HashMap<String, Dog>();
dogMap.put("Fido", new Dog("Fido"));

Dog myPet = dogMap.get("Fido");

Or you can gain references to objects in many other ways such as via arrays, ArrayLists, LinkedLists, or several other collectinos.

Edit
You state:

The thing is that in my code I am going to be using one method to create objects, the name of the object is arbitrary but I need it to be dynamic because it wont be temporary, so the actually name of the object has to change or I will be writing over the previously declared object.

This is exactly what I meant when I said that the name of the variable is not as important as you think it is. The variable name is not the "object name" (this really doesn't exist in fact).

For example if you create a dog in a variable named Fido, and then assign it to a new variable named spot, both variables, despite having different names will refer to the very same object:

Dog fido = new Dog;
Dog spot = fido; // now fido and spot refer to the same object

If you want to give a variable a "name" consider giving the class a name property:

class Dog {
private String name;

public Dog(String name) {
this.name = name;
}

public String getName() {
return name;
}
}

Now you can give each Dog object its own (semi) unique name if you wish.

To use a string value as a variable name

What you can do is by associating (mapping) those values to the Music object. Here is example:

Map<String, Music> musics = new HashMap<>();
String musicPlaying = "music2";
musics.put("music1", new Music("blaalla"));
musics.put("music2", new Music("blalala"));
musics.put("music3", new Music("balaada"));

if(!musics.get(musicPlaying).stillPlaying) { // As you can see i am using string as a variable name.
changeMusic();
}

Set string to variable name

You can store the data in an object with the keys matching your select's values.

var data = {
basketball: "changeable-string",
handball: 760,
football: null,
baseball: "description: ball-game to play"
}

function myFunction(el) {
console.log(data[el.value])
}
<select name="box" onchange="myFunction(this);">
<option value="football">Football</option>
<option value="handball">Handball</option>
<option value="basketball">Basketball</option>
<option value="baseball">Baseball</option>
</select>

convert string value to variable name | string value contain variable name

If the question is, whether you can get the value of a variable knowing its name at runtime, then good news.... Yes for sure you can... you will need to do something called REFFLECTION...

which is allowing you as developer to make an instrocpection of the class and even "browse" all the info that the class is holding

in your case you need to find a "variable" (or Field) by the name and read its value...

look the doc for more info, and I would recommend you to consider if you really need to do this... normally reflection is intended to be used when you want to access info from another class and not about browsing yourself...

you can maybe redesign a little the application and define some constants and methods so other can see what you are exposing to them and making for them available...

Example:

public class Jung {
Double new_val = 10.0;
String a = "new";
String b = "val";
Double v1 = 25.0;
Double result = 0.0;

public void getVal() {
// String variable c contain double variable name
String c = a + "_" + b;
Double cAsVal = 0.0;
try {
cAsVal = dale(c);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
result = v1.doubleValue() * cAsVal.doubleValue();
System.out.println(result);
}

public static void main(String[] args) {
Jung j = new Jung();
j.getVal();
}

public Double dale(String c)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Field field = this.getClass().getDeclaredField(c);
field.setAccessible(true);
Object value = field.get(this);
return (Double) value;
}
}

Use string to create variable name and its value in Python

Just for Django ORM you can pass parameters as a dictionary:

field_name = "status"
value = "joined"

filter_params = {
field_name: value
}

model.objects.filter(**filter_params)

or just:

field_name = "status"
value = "joined"

model.objects.filter(**{field_name: value})

See this page for more details on unpacking a dictionary.

Create variables with names from strings

You can do it with eval but you really should not

eval(['x', num2str(i), ' = ', num2str(i)]); %//Not recommended

Rather use a cell array:

x{i} = i

Convert a String to a Variable name in Python

I just cobbled a quick example to do what you want to do, I do not recommend that you do this, but I will assume that you have a good reason to and will therefore help.

vars = ["a", "b", "c"]
for i in range(len(vars)):
globals()[vars[i]] = (i+1)*10

print(a) # 10
print(b) # 20
print(c) # 30

This example may be a little complicated but it does exactly what you asked for in your question, long story short you can use the globals() function to turn a string into a variable. Link for more info here: https://www.pythonpool.com/python-string-to-variable-name/



Related Topics



Leave a reply



Submit