こんなクラスがあったとします。
java
1class Test { 2 private Double A; 3 private Integer B; 4 private String C; 5 6 public void setTest(Double arg) { A=arg; } 7 public void setTest(Integer arg) { B=arg; } 8 public void setTest(String arg) { C=arg; } 9}
このクラスをリフレクションを使ってスマートに設定する関数を作ろうとしたのですが
getMethodの<<1>>、invokeの<<2>>の第2引数をどう書いていいのかわからず試行錯誤しております。
<<1>>はvalueを元にgetClass()を渡してみましたがNoSuchMethodExceptionのエラーとなります。
java
1Test test = new Test(); 2SetFunc(test, new Double(123.45)); 3SetFunc(test, new Integer(123)); 4SetFunc(test, new String("ABC")); 5 6public void SetFunc(Test cls, Object value) { 7 Method method = cls.getClass().getMethod("setTest", <<1>>); 8 method.invoke(cls, <<2>>); 9}
そもそもこのような場合はSetFuncのvalue引数のクラスによって振り分けるなど
しなければ実現できないのでしょうか?
ご教示の程、よろしくお願い致します。
追記
java
1 2class Test { 3 private float D; 4 private Double A; 5 private Integer B; 6 private String C; 7 8 public void setTest(float arg) { D=arg; } // float型が引数 9 public void setTest(Double arg) { A=arg; } 10 public void setTest(Integer arg) { B=arg; } 11 public void setTest(String arg) { C=arg; } 12} 13
java
1public class JavaApp { 2 3 public static void main(String[] args) throws Exception { 4 Test test = new Test(); 5 SetFunc(test, 123.4f); 6 SetFunc(test, new Double(123.45d)); 7 SetFunc(test, new Integer(123)); 8 SetFunc(test, new String("ABC")); 9 } 10 11 public static void SetFunc(Test cls, Object value) throws Exception { 12 Method method = cls.getClass().getMethod("setTest", value.getClass()); 13 method.invoke(cls, value); 14 } 15} 16 17
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/02/23 03:13 編集
2016/02/23 04:25 編集
2016/02/23 06:04
2016/02/23 06:27
2016/02/23 07:03 編集