简体   繁体   中英

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.

Since your interface is ActivationService<T extends Activator> you'll probably want to use Set<ActivationService<? extends Activator>> 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, ie 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> ActivatorService<? extends Activator> , ie there's no way to get the actual generic type at compiletime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM