ハードセクションのジェネリックを使用して値を設定しようとしている間に、引数型の不一致に問題があります。リフレクションを使用したJavaのプリミティブ型の動的明示的キャスト
public static void Main(String... args) {
int intValue = 1;
long longValue = 1l;
Foo foo = new Foo();
// Easy
foo.setIntValue(intValue);
foo.setLongValue(longValue);
invokeSet(foo, "setIntValue",intValue);
invokeSet(foo, "setLongValue",longValue);
//Medium
foo.setLongValue(intValue);
invokeSet(foo, "setLongValue",intValue);
//Hard
foo.setIntValue((int)longValue); //How to implement this in generic way ?
invokeSet(foo, "setIntValue",longValue);
}
class Foo {
int intValue = 0
long llongValue = 0;
setIntValue(int i) {
this.intValue = i;
}
setLongValue(long l) {
this.longValue = l;
}
}
事は、私は明示的なキャストを予想していたということでしょうか?
EDIT
が行われ、反射型のクラスなどを使用して動的な方法でそれを実行する可能性縮小プリミティブ変換を予想するすべての可能性はありますか? FYI
:
我々は、彼らがもはや原始的プリミティブ型に反射で作業しています。これを達成する
private static void invokeSet(Object bean, String methodName, Object value) throws Exception {
Method m = retriveMethod(bean, methodName);
m.invoke(bean,value); //More or less there is a type wrapper to change primitive to object class
}
EDIT2
一つの方法は、文字列に値を変更して、特定の種類の数の文字列コンストラクタを使用することである値を持つ文字列を渡します。 int
へlong
キャスティング
int intValue = 0;
long longValue = 0l;
Integer intObject = i;
Long longObject = l;
intValue = (int)longValue;
intOBject = new Integer(String.valueOf(longObject)); // intObject = (Integer) longValue; this is not allowed
intObject = longObject.intValue(); //Target to achieve with out writing bad code.
「一般的な方法で」とはどういう意味ですか?明示的なキャストがなければ、 'long 'を' int'に強制しようとしているので、コンパイラは正しく文句を言います。あなたは何をしたいのですか? –
"invokeSet"とは何ですか?リフレクションを使用してBeanに値を設定する関数ですか?あなたはあなたの質問にもっと具体的になりますか? –
@Oli反射を使用しています。私のエラー。 @Luciano、はい、反射を使ってBeanに値を設定する関数です。 –