Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a generic T implements an interface

Tags:

so I have this class in Java:

public class Foo<T>{ } 

and inside this class I want to know if T implements certain interface.

The following code DOES NOT work but it's the idea of what I want to accomplish:

if(T.class implements SomeInterface){     // do stuff } 

so I want to check if the class T that was passed to Foo have implements SomeInterface on its signature.

Is it possible? How?

like image 734
Budius Avatar asked Sep 13 '13 10:09

Budius


People also ask

Can a generic class implement an interface?

Only generic classes can implement generic interfaces. Normal classes can't implement generic interfaces.

Is generic an interface?

A generic interface is primarily a normal interface like any other. It can be used to declare a variable but assigned the appropriate class. It can be returned from a method. It can be passed as argument.

How do you find a generic type?

Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.


Video Answer


2 Answers

Generics, oddly enough, use extends for interfaces as well.1 You'll want to use:

public class Foo<T extends SomeInterface>{     //use T as you wish } 

This is actually a requirement for the implementation, not a true/false check.

For a true/false check, use unbounded generics(class Foo<T>{) and make sure you obtain a Class<T> so you have a refiable type:

if(SomeInterface.class.isAssignableFrom(tClazz)); 

where tClazz is a parameter of type java.lang.Class<T>.

If you get a parameter of refiable type, then it's nothing more than:

if(tParam instanceof SomeInterface){ 

but this won't work with just the generic declaration.

1If you want to require extending a class and multiple interfaces, you can do as follows: <T extends FooClass & BarInterface & Baz> The class(only one, as there is no multiple inheritance in Java) must go first, and any interfaces after that in any order.

like image 70
nanofarad Avatar answered Sep 22 '22 17:09

nanofarad


you can check it using isAssignableFrom

if (YourInterface.class.isAssignableFrom(clazz)) {     ... } 

or to get the array of interface as

Class[] intfs = clazz.getInterfaces(); 
like image 27
muthu Avatar answered Sep 19 '22 17:09

muthu