简体   繁体   中英

Generic method with generic result in Java

I have the following service method:

public static <T> T service(final Class<T> klass) {...}

And I use it this way

SomeService someService = service(SomeService.class);

However, using this approach I can't get generic service, for example what should I do if I need

SomeService<Foo> someService = ???

How to do it? How to make service method signature?

This is one shortcoming of Java - it doesn't have higher-kinded types (you might want to look at this: https://en.wikipedia.org/wiki/Kind_(type_theory) ). This means that a method can't know if it's one of its type parameters takes type arguments and how many arguments it takes. However, assuming you're the author of SomeService and other Service classes, you can define an interface like this:

public interface IService<F> {
 //The rest could be empty
}

//And then
public static <F, T extends IService<F>> T service(final Class<T> klass) {}

However, since you're using reflection, you're already dealing with unsafe operations where type safety isn't guaranteed to be preserved, so having to cast to a SomeService should really be the least of your concerns. If you wish, you could even rewrite your method like this, where T is SomeService and R is SomeService<Foo> :

public static <T, R> R service(final Class<T> klass) {
  T result = ...;
  return (R) result;
}

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