0

I need to use the Reflection API to get exact information on the method parameters of the methods in a class. Consider the following minimal example:

public class A<T> {
  void test(T t, List<String> l) {}
}

public class B extends A<Integer> {
  @Override
  void test(Bar t, List<String> l) {}
}

public class Main{
  public static void main() {
    Method[] methods = B.class.getDeclaredMethods();
    for (Method m : methodsB) {
      System.out.println(m);
      System.out.println(m.getGenericParameterTypes()[1] instanceof ParameterizedType)
    }
  }
}

This will result in

void B.test(java.lang.Integer,java.util.List)
true
void B.test(java.lang.Object,java.util.List)
false

My question is:

  1. why does getDeclaredMethods() output two methods instead of one? If test doesn't have a generic parameter or if it would be a new method of B (not overridden), getDeclaredMethods() will output only one methods, as expected.
  2. what would be a realiable and general way to filter out the "wrong" methods, which don't include generic type information?
Robin
  • 333
  • 1
  • 12
  • 6
    https://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html, [What Method.isBridge used for?](https://stackoverflow.com/q/289731) – Pshemo Feb 15 '22 at 14:55

1 Answers1

0

As Pshemo pointed out, the second, less specific method is a Bridge Method (https://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html) which is used as a means of type erasure.

Bridge methods can be identified using method.isBridge().

Robin
  • 333
  • 1
  • 12