Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8215302

Primitive types boxing doesn't work as described in specification

XMLWordPrintable

      ADDITIONAL SYSTEM INFORMATION :
      Java 11.0.1, java 1.8. Windows 10 machine with latest updates.

      A DESCRIPTION OF THE PROBLEM :
      According to jls-5.1.7 "If the value p being boxed is an integer literal of type int between -128 and 127 inclusive (§3.10.1), or the boolean literal true or false (§3.10.3), or a character literal between '\u0000' and '\u007f' inclusive (§3.10.4), then let a and b be the results of any two boxing conversions of p. It is always the case that a == b."
      However in case of method called via reflection boxed value is always created via `new PrimitiveWrapper()`.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Create a method returning primitive value (boolean will do).
      Call the method via reflection (class.getMethod("methodName").invoke(null))
      Compare resulting value with expected.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      true
      true
      true
      true
      true
      ACTUAL -
      false
      true
      true
      false
      true

      ---------- BEGIN SOURCE ----------
      public class ReflectionTest {
          public static boolean testTrue() {
              return true;
          }

          public static int test42() {
              return 42;
          }

          public static void main(String[] args) throws Exception {
              final Object trueResult = ReflectionTest.class.getMethod("testTrue").invoke(null);
              final Object trueResult2 = testTrue();
              final Object test42Result = ReflectionTest.class.getMethod("test42").invoke(null);

              System.out.println(trueResult == Boolean.TRUE);
              System.out.println(trueResult2 == Boolean.TRUE);
              System.out.println(Boolean.TRUE.equals(trueResult));
              System.out.println(Integer.valueOf(42) == test42Result);
              System.out.println(Integer.valueOf(42).equals(test42Result));
          }
      }

      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      Use BoxedType.equals() instead for raw ==

      FREQUENCY : always


            mchung Mandy Chung (Inactive)
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: