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?
The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.
Filter out bridge methods:
Method[] methods = Arrays.stream(StringImpl.class.getDeclaredMethods())
.filter(m -> !m.isBridge())
.toArray(Method[]::new);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With