これをネイティブに行う方法は 2 つありますが、ネイティブではない方法が 1 つあります。
オプション1
あなたが持っているのはオプション1です。それはほとんど正しいです。間違った比較方法を使用しているだけです。あなたのものを比較してください
public void processArgument(Instruction info) {
// this is bad - uses reference comparison
if (info.command == "read")
int value = manager.read(info.objectName);
}
推奨と
public void processArgument(Instruction info) {
// this is good - actually compares the values
if (info.command.equals("read"))
int value = manager.read(info.objectName);
}
info.command
が null の場合、これは例外をスローしないため、次のことを行う方がさらに良いと考える人もいます。個人的には、例外を取得したいので、それは好きではありませんが、多くの人がそれを支持しており、そうするのに完全に正当な理由があります。
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);
}
もちろん、振る舞いを追加すると、if ステートメントを追加するだけです。
Java 7 では、これを行うことができます。
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");
}
}
オプション 2
別のオプションは、次のように匿名クラスを利用する Map を使用することです。
// 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); }
}
次に、引数を呼び出すとき
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);
}
オプション 3
SagarDabas が彼の投稿で概説しているように、リフレクションを使用します。これには特別なアクセス許可が必要な場合があり、正確性オプションの柔軟性が得られないことに注意してください。