How do I determine whether Java generics implement specific interfaces?
•
Java
How do I determine whether Java generics implement specific interfaces?
I tried several different methods, but they all led to the error of "unable to find symbol... Variable t"
First attempt
public abstract class AbstractClass<T> { public void doFoo() { if (T instanceof SomeInterface){ // do stuff } } }
Second attempt
public abstract class AbstractClass<T> { public void doFoo() { if (SomeInterface.class.isAssignableFrom(T)) { // do stuff } } }
Solution
You can’t.
Solution 1
Add a constructor using the class of the object
public abstract class AbstractClass<T> { private Class<T> clazz; public AbstractClass(Class<T> clazz) { this.clazz = clazz; } public void doFoo() { if (clazz instanceof SomeInterface){ // do stuff } } }
Solution 2
Add constraints to type T and use t to extend someinterface, limiting type T to subtypes of someinterface
public abstract class AbstractClass<T extends SomeInterface> { public void doFoo() { // do stuff } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码