I have the following interface: interface Nofifier<T> { }
.
I have the following implementation: class MyClass implements Notifier<String>, Notifier<Integer> { }
.
Is there a way I can query from:
MyClass instance = new MyClass();
Class<?> clazz = instance.getClass();
// ...
to get the types of Notifier
that MyClass
implements?
Yes - you can call Class.getGenericInterfaces()
, which returns a Type[]
. That includes type argument information.
Complete example:
import java.lang.reflect.Type;
interface Notifier<T> { }
class Foo implements Notifier<String> {
}
class Test {
public static void main(String[] args) {
Class<?> clazz = Foo.class;
for (Type iface : clazz.getGenericInterfaces()) {
System.out.println(iface);
}
}
}
However, you can't implement the same interface twice on one class anyway, so your class MyClass implements Notifier<String>, Notifier<Integer>
shouldn't compile. You should get an error such as:
error: Notifier cannot be inherited with different arguments:
<java.lang.String> and <java.lang.Integer>
From JLS 8.1.5:
A class may not at the same time be a subtype of two interface types which are different parameterizations of the same generic interface (ยง9.1.2), or a subtype of a parameterization of a generic interface and a raw type naming that same generic interface, or a compile-time error occurs.
See more on this question at Stackoverflow