There's two ways to natively do this, and one less native way.
- If statements
- Functor map
- Reflection
Option 1
What you have is option 1, and it's mostly correct, you just are using the wrong way of comparison. Compare yours
public void processArgument(Instruction info) {
// this is bad - uses reference comparison
if (info.command == "read")
int value = manager.read(info.objectName);
}
with the recommended
public void processArgument(Instruction info) {
// this is good - actually compares the values
if (info.command.equals("read"))
int value = manager.read(info.objectName);
}
Some would consider it even better to do the following because if info.command
is null this will not throw an exception. Personally I don't like that because I'd rather get the exception, but many people advocate it, and they have a perfectly valid reason for doing it.
public void processArgument(Instruction info) {
// "read" can never be null, so no null pointer exception here
if ("read".equals(info) )
int value = manager.read(info.objectName);
}
Of course, as you add more behaviours, you just add more if statements.
In Java 7, you can do this:
public void processArgument(Instruction info) {
switch(info.command) {
case "read": manager.read(info.objectName); break;
case "write": manager.write(info.objectName); break;
default: throw new IllegalArgumentException("Command " + info.command + " not supported");
}
}
Option 2
Another option is to use a Map utilizing anonymous classes, like so:
// define this somewhere
abstract class Functor {
Manager m;
Functor(Manager m) { this.m = m; }
void execute(Instruction info);
}
// somewhere you have access to
Map<String,Functor> funcs = new HashMap<String,Functor>();
// add this to a static block, or constructor, depending
funcs.put("read", new Functor(manager) {
public void execute(Instruction info) { m.read(info.objectName); }
});
funcs.put("write", new Functor(manager) {
public void execute(Instruction info) { m.write(info.objectName); }
}
Then when you call your arguments
public void processArgument(Instruction info) {
Functor f = funcs.get(info.command);
if(f == null) throw new IllegalArgumentException("Operation " + info.command + " not supported");
f.execute(info);
}
Option 3
Use reflection as SagarDabas outlines in his post. Note that this may require special access permissions, and is not going to give you as flexible of correctness options.