3 Replies Latest reply on Nov 4, 2010 1:30 PM by 810555

    Reflection API - Inaccurate Results?

      The reflection API appears to be telling me that a method exists that does not really exist. Here is the simplistic example; given the following class:

      import java.util.HashMap;
      public class StringMap extends HashMap<String, Object> {

      public java.lang.Object put(String s, Object o)
      super.put(s, o);
      return null;

      If I examine this class with the reflection API I am told that two "put" methods exist; one that takes "String, Object" as parameters and one that takes "Object, Object" as parameters.

      Class clss = StringMap.class;
      for (Method m: clss.getDeclaredMethods()) {

      produces the output of:
      public java.lang.Object StringMap.put(java.lang.String,java.lang.Object)
      public java.lang.Object StringMap.put(java.lang.Object,java.lang.Object)

      Why would the reflection API indicate that there is a form of put that takes two objects? Especially since I am using getDeclaredMethods() instead of getMethods()? I can't find a way to differentiate between these two using the reflection API (other than I know the one that takes Object,Object is not valid in code). This is causing a problem as I am generating psuedo test cases via reflection and the generated code won't compile because put(Object,Object) doesn't exist in StringMap. Thoughts? Is there a way I am missing to differentiate between these two? Is this a bug?


        • 1. Re: Reflection API - Inaccurate Results?
          The extra method is generated by the compiler as part of Generics. It is a thunk to the other one.
          • 2. Re: Reflection API - Inaccurate Results?
            Ok, now I know what it is... But I still get compiler errors if I generate code that tries to call it. Is there anyway to tell that the method is not actually callable from code (and it is just an artifact of the generics)?

            My code reflects on a JAR file and spits out something akin to a test case and because StringMap.put(Object,Object) is identified as a method via reflection, my code generates a call to it:

            obj.put(arg0, arg1);

            Yes, when this is compiled you get:

            ...\test.java:177: cannot find symbol
            symbol : method put(java.lang.Object,java.lang.Object)
            location: class StringMap
            obj.put(arg0, arg1);

            Any ideas?


            • 3. Re: Reflection API - Inaccurate Results?
              I just figured this out. Thanks for pointing out that this was generated by the compiler - Method.isSynthetic() returns "true" for methods like this.