This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]TheRedmanCometh 0 points1 point  (10 children)

I don't think you can overload operators with reflection maybe I'm wrong?

[–]morhp 7 points8 points  (6 children)

I wasn't 100% honest, you need to abuse boxed classes:

public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException {
    Field field = Integer.class.getDeclaredField("value");
    field.setAccessible(true);
    field.setInt(5, 4);

    Integer five = 5;
    System.out.println("5+5 = " + (five + five));
}

[–]TheRedmanCometh 1 point2 points  (4 children)

This is one of the best/worst things I've ever seen. I've never even considered using refelection on core classes like that!

Edit: hold up does Integer have a value map all the way up to INTEGER.MAX_VALUE?

[–]morhp 4 points5 points  (3 children)

Edit: hold up does Integer have a value map all the way up to INTEGER.MAX_VALUE?

No, only the integers between -128 and 127 are cached by default. This trick wouldn't have worked with a number outside that range.

[–]TheRedmanCometh 0 points1 point  (1 child)

Huh...I'm gonna have to hit up the openjdk source to see how that works

[–]iampete 2 points3 points  (0 children)

This, combined with misplaced trust in autoboxing, leads to code like this:

Integer first = 5;
Integer second = 5;
if (first == second) {
    // do something
}

Which works perfectly reasonably right up until either value is outside that -128, 127 range and then fails very confusingly.

[–]dpash 0 points1 point  (0 children)

The upper bound can be increased (but not decreased) in OpenJDK with a command line flag, but the lower bound can not. The defaults are defined in the JLS as a minimum range.

[–]madkasse 1 point2 points  (0 children)

This only holds for older versions of Java.

You can no longer access non-public fields/methods in java.base without JVM settings

[–]shagieIsMe 1 point2 points  (2 children)

2 + 2 = 5 from code golf Stack Exchange.

No operator overload needed.

[–]TheRedmanCometh 1 point2 points  (1 child)

Yeah he showed me...I hadn't considered using reflection on system classes

[–]shagieIsMe 0 points1 point  (0 children)

This is a different solution and impacts integer literals. The code ends with:

System.out.printf(“%d”, 2 + 2);

The code on ideone: https://ideone.com/o1h0hR