Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get concrete type of a generic interface

Tags:

I have an interface

public interface FooBar<T> { } 

I have a class that implements it

public class BarFoo implements FooBar<Person> { }

With reflection, I want to take an instance of BarFoo and get that the version of FooBar it implements is Person.

I use .getInterfaces from BarFoo to get back to FooBar, but that doesn't help me find out what T is.

like image 605
bwawok Avatar asked Jul 14 '10 14:07

bwawok


People also ask

Can a generic type be an interface?

We can subtype a generic class or interface by extending or implementing it. The relationship between the type parameters of one class or interface and the type parameters of another are determined by the extends and implements clauses.

How is a generic interface defined?

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.

Can you create an instance of generic interface?

You cant create an instance of an Interface.


2 Answers

You can grab generic interfaces of a class by Class#getGenericInterfaces() which you then in turn check if it's a ParameterizedType and then grab the actual type arguments accordingly.

Type[] genericInterfaces = BarFoo.class.getGenericInterfaces(); for (Type genericInterface : genericInterfaces) {     if (genericInterface instanceof ParameterizedType) {         Type[] genericTypes = ((ParameterizedType) genericInterface).getActualTypeArguments();         for (Type genericType : genericTypes) {             System.out.println("Generic type: " + genericType);         }     } } 
like image 98
BalusC Avatar answered Oct 05 '22 11:10

BalusC


Try something like the following:

Class<T> thisClass = null; Type type = getClass().getGenericSuperclass(); if (type instanceof ParameterizedType) {     ParameterizedType parameterizedType = (ParameterizedType) type;     Type[] typeArguments = parameterizedType.getActualTypeArguments();     thisClass = (Class<T>) typeArguments[0]; } 
like image 38
matt b Avatar answered Oct 05 '22 12:10

matt b