1

That is my code.why the reflect api return both methods?

I defined an interface,like this:

import java.util.List;

public interface Species<T> {
    T feed(List<String> numList);
}

the Animal is the implement class of Species:

import lombok.Data;

import java.util.List;

@Data
public class Animal<T> implements Species<T> {


    private T t;

    @Override
    public T feed(List<String> numList) {
        return t;
    }

}
 

the Dog class is a child of Animal class:

import java.util.List;


public class Dog extends Animal<String>{

    @Override
    public String feed(List<String> numList) {
        return "dog feed method";
    }
}

This is my test class,its:


public class TypeTest {


    public static void main(String[] args) {
        Class<Dog> dogClass = Dog.class;
        Method[] declaredMethods = dogClass.getDeclaredMethods();
        for(Method m:declaredMethods){
            System.out.println(m.getReturnType().getName());
        }

    }
}

the run output:

java.lang.String
java.lang.Object

check the variable declaredMethods

enter image description here

nonoy
  • 11
  • 1

1 Answers1

4

Dog indeed has two declared feed methods. The one that returns Object is the bridge method for the one that returns String. The bridge method is generated by the compiler.

The implementation of the bridge method can be summarised as: just cast the parameters to the right types, and call your actual String-returning feed, and return what it returns.

A bridge method is needed because of type erasure. As far as the JVM is concerned, the interface method returns Object, so as an implementing class, Dog gotta have a method that returns Object too. The JVM can't magically find the String-returning method when you are calling feed through the Animal interface. It doesn't care about generics after all.

Sweeper
  • 213,210
  • 22
  • 193
  • 313