简体   繁体   English

Java中具有泛型结果的泛型方法

[英]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) ).这是 Java 的一个缺点——它没有更高级的类型(你可能想看看这个: 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:但是,假设您是 SomeService 和其他 Service 类的作者,您可以定义这样的接口:

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.但是,由于您使用的是反射,因此您已经在处理不能保证保留类型安全的不安全操作,因此必须强制转换为 SomeService 应该是您最不关心的问题。 If you wish, you could even rewrite your method like this, where T is SomeService and R is SomeService<Foo> :如果你愿意,你甚至可以像这样重写你的方法,其中 T 是SomeService而 R 是SomeService<Foo>

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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