title: Dynamic explicit cast of primitive types in Java using reflection
body: <p>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. </p>
  
  <pre><code> 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;
    }
  </code></pre>
  
  <p>}</p>
  
  <p>The thing is that I had to anticipate the explicit cast ? </p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Is there any possibility to anticipate the <em>narrowing primitive conversions</em> might take place and perform it in dynamic way using reflection types class etc.?</p>
  
  <p>FYI: </p>
  
  <p>When we are working with reflection on primitive types they are no longer primitive. </p>
  
  <pre><code>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
  }
  </code></pre>
  
  <p><strong>EDIT2</strong></p>
  
  <p>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. </p>
  
  <pre><code>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.
  </code></pre>