getMethods() returns method I haven't defined when implementing a generic interface

interface, java, reflection

Solution

The first method is a bridge method, created by the compiler. If you test your methods for 'isBridge()', you can filter out the 'wrong' methods (also filters out some strange results you can get with covariance returns).

Following code will not print the `myMethod java.lang.Object`:

import java.lang.reflect.Method;


public class FooImpl implements Foo<String> {
    public void myMethod(String arg) {
    }

    public static void main(String[] args) throws Exception {
        Class cls = FooImpl.class;
        for (Method method : cls.getMethods()) {
            if (!method.isBridge()) {
                System.out.print(method.getName() + "\t");

                for (Class paramCls : method.getParameterTypes()) {

                    System.out.print(paramCls.getName() + ",");

                }
            }
            System.out.println();
        }
    }
}

interface Foo<T> {
    public void myMethod(T arg);
}

Problem

An simple interface: ``` interface Foo { void myMethod(String arg); } class FooImpl implements Foo { void myMethod(String arg){} public static void main(String[] args) { Class cls = FooImpl.class; try { for (Method method : cls.getMethods()) { System.out.print(method.getName() + "\t"); for(Class paramCls : method.getParameterTypes()){ System.out.print(paramCls.getName() + ","); } System.out.println(); } } catch (SecurityException e) { // TODO Auto-generated catch block } } } ``` The output would be: ``` myMethod java.lang.String, ...//Other Method ``` Only one myMethod is printed. But if I change the interface to a generic one: ``` interface Foo<T> { void myMethod(T arg); } class FooImpl implements Foo<String> { void myMethod(String arg){} } ``` Then strangely the output will be: ``` myMethod java.lang.Object, myMethod java.lang.String, ...//Other Method ``` Why after changing the interface to a generic one will lead to one more Method with a parameter type Object?

Original source