I've a problem with argument type mismatch while I'm try to set a values like it is presented using generics in hard section.
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;
}
}
The thing is that I had to anticipate the explicit cast ?
EDIT
Is there any possibility to anticipate the narrowing primitive conversions might take place and perform it in dynamic way using reflection types class etc.?
FYI:
When we are working with reflection on primitive types they are no longer primitive.
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
One way to achieve this is to change the value to string and then using the string constructor in specific type number pass the string with value.
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.
longinto anint. What do you want it to do?