fedd
fedd

Reputation: 941

Get generic type parameters from an object in Java

I am probably wrong with terminology which doesn't help me to google the answer, but the question boils down to this:

I have a set of objects declared like this:

public interface ActivationService<T extends Activator> {
    T getActivator(Item item);
}

, so the set is declared like this:

Set<ActivationService>_activationServices = new HashSet<>();

I want to transform it into a map in order to lookup the appropriate "activation service" easier.

Map<Class<? extends Activator>, Set<ActivationService>> _actsCache = new HashMap<>();

Once I know how to get this T parameter from an object of a class, I will be able to do it. How do I get this from an object? The TypeVariable interface confuses me.

Upvotes: 0

Views: 74

Answers (1)

Thomas
Thomas

Reputation: 88757

Since your interface is ActivationService<T extends Activator> you'll probably want to use Set<ActivationService<? extends Activator>> as well.

That being said, you should already see that there's a problem getting the actual generic type of a service stored in the map/set because it could be any number of unrelated activators.

To fill the map you could do one of 2 things:

  1. Provide a Class<T> getActivatorClass() method in the interface and provide an appropriate implementation.
  2. Use reflection to get the actual generic type from any concrete implementation, i.e. this would work for MyActivatorService implements ActivatorService<MyActivator> but not MyActivatorService<T extends MyActivator> implements ActivatorService<T>. (Have a look here on one way how to do that which I've used for years now [there might be a more modern way now]: https://www.artima.com/weblogs/viewpost.jsp?thread=208860)

Note that when working with such a service you'd need to use some casts eventually because all you've got is a ActivatorService<? extends Activator>, i.e. there's no way to get the actual generic type at compiletime.

Upvotes: 1

Related Questions