Java – getmethods () return method I didn’t define when I implemented the general interface

A 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 will be:

myMethod java.lang.String,...//Other Method

Print only one mymethod

But if I change the interface to a general interface:

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

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

Then it's strange that the output will be:

myMethod java.lang.Object,myMethod java.lang.String,...//Other Method

Why does changing the interface to a general interface lead to a method with parameter type object?

Solution

The first method is the bridge method created by the compiler

The following code will not print 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);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>