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

Arrays.stream with reflection causes compilation error in JDK 8

XMLWordPrintable

    • generic
    • generic

      ADDITIONAL SYSTEM INFORMATION :
      D:\project\untitled\src>ver
      Microsoft Windows [version 10.0.22631.4602]

      D:\project\untitled\src>java -version
      openjdk version "1.8.0_432-432"
      OpenJDK Runtime Environment (build 1.8.0_432-432-b06)
      OpenJDK 64-Bit Server VM (build 25.432-b06, mixed mode)

      D:\project\untitled\src>javac -version
      javac 1.8.0_432-432


      A DESCRIPTION OF THE PROBLEM :
      In the following code, when using a lambda expression in the stream operation (field -> field.getName()), the code results in a compilation error in JDK 8. However, using a method reference (Field::getName) works fine in JDK 8.
      The code also works correctly in JDK 11 and later, regardless of whether a method reference or lambda expression is used.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      compile success
      ACTUAL -
      compile error

      ---------- BEGIN SOURCE ----------
      import java.util.Arrays;
      import java.util.stream.Collectors;

      public class Main {

          private static final String BAR = "SomeStringPrefix" +
                  Arrays.stream(Foo.class.getDeclaredFields())
                          .map(field -> {
                              return field.getName();
                          }).collect(Collectors.joining(","));

          public static void main(String[] args) {
              System.out.println(BAR);
          }
      }

      class Foo {
          private String field1;
          private String field2;
      }
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      import java.lang.reflect.Field;
      import java.util.Arrays;
      import java.util.stream.Collectors;

      public class Main {

          private static final String BAR = "SomeStringPrefix" +
                  Arrays.stream(Foo.class.getDeclaredFields())
                          .map(Field::getName).collect(Collectors.joining(","));

          public static void main(String[] args) {
              System.out.println(BAR);
          }
      }

      class Foo {
          private String field1;
          private String field2;
      }

      FREQUENCY : always


            Unassigned Unassigned
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: