Tag: generics

Nasty bug with generics and introspection

April 19th, 2010 — 5:15pm
public class Test {
  2.   public static interface Foo {
  3.     public T getX();
  4.   }
  6.   public static class Bar implements Foo {
  7.     public String getX() {
  8.       return "Hello World";
  9.     }
  10.   }
  12.   public static void main(String[] args) {
  13.     Method[] methods = Bar.class.getDeclaredMethods();
  15.     for (Method method : methods) {
  16.       System.out.println(method.getReturnType().toString()+" "+method.getName());
  17.     }
  18.   }
  19. }

Will return :

class java.lang.String getX
  1. class java.lang.Object getX

A) It’s illegal in Java to have two methods with the same signature returning different types.

B) The order in which these methods are returned would be completely random. For example, this can cause BeanUtils.copyProperties(..) to intermittently fail to copy some bean properties. BeanUtils would take the first get method returned, find that the return type is not matching corresponding set method and skip it.

The bug is present in both Java 5 and 6. There are several bugs filed around this problem. For example: 6422403 and 6528714. The bad news is that this is not going to be fixed until Java 7.

This is not a bug but a feature. One of the methods returned by introspection is synthetic. Unfortuntely, code written for Java prior to 1.5 like Commons BeanUtils do not recognize this and will break in described situation.

Comment » | Software

Back to top