0

Let's say I have a class myClass and a String myString. How would I do this:

myClass [value of myString] = new myClass;
1
  • 1
    Using a string value as a variable? You can't. Is there a reason why you want to do this? Commented Mar 27, 2013 at 22:50

4 Answers 4

2

You can't have a dynamic variable in Java. Still, you can use a Map<String, Object> to have the String myString as the key and set the new value as new instance of your class:

Map<String, Object> map = new HashMap<String, Object>();
map.put(myString, new MyClass());

If you're sure your map will only contain MyClass instances, then you can use Map<String, MyClass>.

Map<String, MyClass> map = new HashMap<String, MyClass>();
Sign up to request clarification or add additional context in comments.

Comments

1

You cannot use the value of a string variable as a variable name. Java doesn't allow that.

However, with a Map, you can associate a string (as a key) to a value:

Map<String, MyClass> map = new HashMap<String, MyClass>();
map.put(myString, new MyClass());

It's not exactly what you're looking for, but in Java, that's as close as you're going to get.

3 Comments

looks like we have the same idea and took the same time to write our answers.
How is strong typing relevant? It's more about compile-time naming :)
@Armen, I don't think strong typing has anything to do with it. The Java compiler expects variable identifier names to have a name directly in the source file at compile time, and the identifier is not reliant, and cannot be reliant, on any runtime value such as the value of myString.
0

Use a map to store your Objects indexed by your String

public static void main(String[] args) {
    final String myString = "something";
    final Map<String, Object> map = new HashMap<String, Object>();
    map.put(myString, new Object());
}

Comments

0

what about using generics and creating a base class with type parameters

public MyGenClass<K,V>{
 private Map<K,V> map = new HashMap<K,v>();

 public Map<K,V> getMap(){
  return map;
 }

 public void setMap(Map<K,V> iMap){
   map=iMap;
 }

}

using this class, you can easily get different kind of maps while having similar methods.

enjoy :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.