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

Clarify behavior of Class.getField(name) for multiple fields of same name

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Unresolved
    • Icon: P4 P4
    • None
    • None
    • core-libs

      A DESCRIPTION OF THE PROBLEM :
      The Javadoc of java.lang.Class.getField(name) says:

      "If C declares a public field with the name specified, that is the field to be reflected."

      It neglects to explain what it does when there are multiple fields of the same name.
      Worse, it neglects to even mention the possibility, acting as if name<=>field is a bijective map. It is not! (JVMS §4.5: "No two fields in one class file may have the same name and descriptor".)

      I have found experimentally it appears to choose the first field of that name in the class file, which is logical. But maybe you don't want to commit to that implementation (despite Hyrum's Law probably rendering it unchangeable). I notice that getFields() and getDeclaredFields() both say "The elements in the returned array are not sorted and are not in any particular order." even though they do appear to preserve the class file order. Whatever.

      getField(name) and getDeclaredField(name) should both include some clarification like:

      "The Java virtual machine identifies fields by both name and type, so it fully allows a class to declare multiple fields of the same name if they have different types, even though the Java language forbids this. If there are multiple matching fields, one is chosen arbitrarily."

      Note that getMethod(name, parameterTypes...) is already fully explicit about the fact that there may be multiple matching methods in the class file and it explains how one is chosen, so there is no problem there.


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

              Created:
              Updated: