Skip to main content

Bizarre behaviour in PropertyDescriptor

Posted by mister__m on November 29, 2004 at 9:26 AM PST

I've just found out the most bizarre bug I've ever come accross in my 5 years of experience with the Java platform. Let's suppose you have the following code:

import java.beans.*;

public class BizarreBean {
   public static class B1 {
      public String getProperty() {
         return null;
      }
   }

   public static class B2 extends B1 {
      public String getProperty() {
         return null;
      }
   }

   public static void main(String[] args) throws Exception {
      PropertyDescriptor[] pd = Introspector.getBeanInfo(B2.class)
            .getPropertyDescriptors();

      for (int i = 0; i < pd.length; i++) {
         if (!pd[i].getName().equals("property")) {
            continue;
         }

         System.out.println(pd[i].getReadMethod());
         break;
      }
   }
}

Basically there are two JavaBean classes, B1 and B2. B2 extends B1 and override the getter method for property. BizarreBean.main(String[]) just retrieves an array of PropertyDescriptors from B2's BeanInfo instance and then print the read method for property. The output for this will be:

public java.lang.String BizarreBean$B2.getProperty()

But what happens if a setter is defined for property? If B1 and B2 are changed like this:

   public static class B1 {
      public String getProperty() {
         return null;
      }

      public void setProperty(String property) {
      }
   }

   public static class B2 extends B1 {
      public String getProperty() {
         return null;
      }

      public void setProperty(String property) {
      }
   }

Then the output becomes:

public java.lang.String BizarreBean$B1.getProperty()

What is the logic behind this? None. This is one of the most awkward bugs I've ever found in J2SE. Unless anyone is able to explain in a reasonable way why this is not bug (I seriously doubt anyone will be able to), I'll file a bug report in the bug parade.

Related Topics >>