0

I am new to Java reflection. I am trying to make a program where addition of two numbers gives custom result. Below is the code:

public class MoreTest {

    public static void main(String[] args) {

        try {
            Field field = Integer.class.getDeclaredField( "value" );
            field.setAccessible( true );
            field.setInt(Integer.valueOf(2),2);             

        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }

        System.out.println( 2 + 4 ); // should print 8
    }

}

What I can do in the above code to print the output I need?

Bogl
  • 125
  • 2
  • 11
  • 1
    Are you trying to make an [integer bomb](https://thedailywtf.com/articles/Disgruntled-Bomb-Java-Edition)? –  Jun 07 '17 at 15:38
  • Why you expect it should print 8 – gati sahu Jun 07 '17 at 15:39
  • @RC., Yes, I was trying for the same as I read there and was just playing with the reflection to know its power. – Bogl Jun 07 '17 at 15:47
  • So your issue is as stated in bowmore answer the "set" on the field, it's `setInt(target object, new value)` and off course you have to use the `Integer` object (see also https://stackoverflow.com/questions/20897020/why-integer-class-caching-values-in-the-range-128-to-127 for the why this is possible) –  Jun 07 '17 at 15:52

1 Answers1

0

Well you just rewrite 2 to... 2 instead of 4...

try replacing this :

field.setInt(Integer.valueOf(2), 2);

by this

field.setInt(Integer.valueOf(2), 4);

in your code

Then :

Integer a = 2;
System.out.println( a + 4 ); // will print 8

This works because Integer a = 2; triggers autoboxing, the compiler replaces this with Integer a = Integer.valueOf(2);, which is the instance from the cache you doctored earlier to have value 4.

In the expression a + 4 auto-unboxing is used; the compiler replaces that with a.intValue() + 4.

In the expression 2 + 4 (using numeric int literals) the values are both primitives, and no Integerclass instances are used.

bowmore
  • 10,842
  • 1
  • 35
  • 43
  • It is not printing like this, but when I make it to `System.out.println( (Integer)2+(Integer)2 );`, it works. Can you explain me how it works as per your solution if suppose I need to print `2+2` should be `5`. Thanks – Bogl Jun 07 '17 at 15:52
  • you can't make `2+2` print 5. these numeric numerals are backed by the primitive `int` type, not the `Integer` class – bowmore Jun 07 '17 at 16:37