Reputation: 13
I have some variables defined like this.
public final static String pDrive = "\\\\fs-innova1\\projects\\";
public final static String hDrive = "\\\\fs-innova1\\hr-department\\";
public final static String iDrive = "\\\\fs-innova1\\innova\\";
Then later in my program I have a string that says "p:\blah\blah\blah" I would like to look at the first char in that string and call the variable like Char(0)+"Drive
Upvotes: 0
Views: 214
Reputation: 510
It is impossible to name variables at runtime. Your best bet is to use a map.
Upvotes: 0
Reputation: 1500525
You should use a Map<String, String>
instead:
private static final Map<String, String> DRIVE_MAPPINGS = new HashMap<>();
static {
DRIVE_MAPPINGS.put("p", "\\\\fs-innova1\\projects\\");
DRIVE_MAPPINGS.put("h", "\\\\fs-innova1\\hr-department\\");
DRIVE_MAPPINGS.put("i", "\\\\fs-innova1\\innova\\");
}
Then use
String mapping = DRIVE_MAPPINGS.get(input.substring(0, 1));
(Alternatively, if you're really only ever going to want the key to be a single character, use a Map<Character, String>
- it's the same idea.)
I would personally create an immutable map using Guava, but again the principle is the same - that would just make it obvious that you weren't going to change the contents of the map after construction.
Upvotes: 3