Search code examples
javareflectionintegerprimitive

Java Reflection ~ Set Inner Object Value Of A Primitive Type


I have an object that is either type of int, short, byte or long and I need to give it a new value. Would that be possible in Java ? And if yes how ?

public static void set(Object obj, int value) throws Exception
{
    Class<?> c = obj.getClass();
    if (c.equals(Integer.class))
    {
        // ???
    }
}

Solution

  • Integer is immutable. You cannot set a value to an Integer instance.

    Similarly, other wrapper classes for primitive types are also immutable.