问题
I was wondering if in Java there was any way to give a new variable a name which is the value of another variable. The below code is an non working example of what I'm trying to do.
int a = 0;
while(true){
String (a) = "newValue";
a = a + 1;
}
or
String b = "newVariableName";
int (b) = 1;
Thank for any help given.
回答1:
You cannot create dynamic variable names in Java. I would recommend placing these variables in a Map with a string as a key. The key can be whatever String you would like.
回答2:
No this is not possible. It is possible to create a new object and add it to an array or some sort of list. Then you can reference the new object by the subscript. So a rough example could be:
Object[] a = new Object[30];
for(int i = 0; i < 30; i++)
{
a[i] = new Object();
}
and then you could use
a[some number].someFunction();
If you think about it, how can the compiler know what the value of a certain true variable is going to be, outside of the actual program run time? It is unlikely that you need to actually do what you want however.
回答3:
You're trying to make an array or a list or a dictionary.
回答4:
You can't do this. Use a Dictionary or a Map to store the values.
回答5:
No, there's no way to do such a thing in Java. The closest you could do would be to create code at runtime and load a new class with fields made with dynamic names.
You might want to consider something simpler like a HashMap instance.
回答6:
I dont think reflection will help because there is no way how to create new instance of Field. So something like
Map<String,Field>
wont work. Use javascript instead :)
来源:https://stackoverflow.com/questions/9152439/java-variable-value-as-new-variable-name