Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 239
Ukonn Ra Avatar asked May 14 '18 14:05

Ukonn Ra


People also ask

How do I get a class instance of generic type T?

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.


1 Answers

Filter out bridge methods:

Method[] methods = Arrays.stream(StringImpl.class.getDeclaredMethods())
                         .filter(m -> !m.isBridge())
                         .toArray(Method[]::new);
like image 134
Andrew Tobilko Avatar answered Oct 08 '22 13:10

Andrew Tobilko