How to just get the method in the implement class with a generic interface in Java

  • A+
Category:Languages

here I have a generic interface and a class implementing it.

import java.util.Arrays;  interface Interface<T> {     void doSomething(T element); }  class StringImpl implements Interface<String> {     @Override     public void doSomething(String element) {         System.out.println("StringImpl: doSomething");     } }  public class Main {     public static void main(String... args) {         System.out.println(Arrays.toString(StringImpl.class.getDeclaredMethods()));     } } 

And the result is

[public void com.ra.StringImpl.doSomething(java.lang.String),  public void com.ra.StringImpl.doSomething(java.lang.Object)] 

But in fact, I just want the implementing version:

public void com.ra.StringImpl.doSomething(java.lang.String) 

Do you have any convient way to achieve it?


Filter out bridge methods:

Method[] methods = Arrays.stream(StringImpl.class.getDeclaredMethods())                          .filter(m -> !m.isBridge())                          .toArray(Method[]::new); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: