0

I would like to save some work on my app, is it possible to get the string, for example "level1" and then use the corresponding function, which would be level1();? my main point is not to make a huge switch-case statement, but only make a few level functions in a storage class, and whenever you level up, the string would change to "level" + number where number is the int, so lets say that right now you are in level 10, the function that would run is level10();

I hope i explained it clearly.. sorry if not.. hope you get the idea!

Thanks!

4

4 に答える 4

3

名前を文字列として使用して、実行時にメソッドを呼び出したいと思います。

リフレクションを介してそれを行うことができます。

Class.getMethod(String methodName, Class... parameterTypes)

于 2012-07-31T13:06:54.137 に答える
2

リフレクションをいじくり回したくない限り、これをメソッド名の観点から考えないでください (そうしたくないし、必要もありません)。

本当に文字列をメソッド呼び出しに変換する必要がある場合(これは大きな "if" です)、 "callable" のようなインターフェイスを実装するMap<String, Foo>whereを作成します。Foo次に、文字列からメソッドへのルックアップは単純です。

Map<String, Foo> commands = /* ... */;
Foo foo = commands.get("level42");
foo.bar();
于 2012-07-31T13:07:11.070 に答える
1

それは本当にあなたが持っているべきであるように聞こえます

void setLevel(int level)

電話。レベル 11 ~ 14 などを (たとえば) 無視してもかまいませんが、別々のメソッドを用意して名前で呼び出すのは非常に見苦しいものです。リフレクションを使用してこれを行うことができますが、最初に他のオプションを検討する必要があります。

于 2012-07-31T13:06:38.743 に答える
0

この投稿に対するトップの回答を参照してください。

Java 動的関数呼び出し

リフレクションを使用する代わりに、よりオブジェクト指向のソリューションを作成するために、構造に関する彼らのアドバイスに従うこともお勧めします。

于 2012-07-31T13:06:30.270 に答える