Java 基于 string/enum 或 class 属性 推导通用对象 class 的惯用方法是什么?
What is the Java idiomatic way to deduce generic object class based on string/enum or class property?
我正在使用来自具有以下签名的外部 Maven 依赖项的 API:
public <T> T get(String key, Class<T> responseType)
API return 是一个 T
类型的对象,用于键值存储中的给定键。
在我的应用程序中有几种对象类型可以 returned,例如:Product
、Customer
等
我想将外部 API 包装到我的服务中,它将接收一个密钥并 return 找到的对象。我不知道如何从服务中 return 对象类型。以下是我的尝试:
public class MyService {
public <T> T get(String key, String objType) {
Class clazz = null;
if (objType == "Customer") {
clazz = Customer.class;
} else if (objType == "Product") {
clazz = Product.class;
}
return externalApi.get(key, clazz); // doesn't compile
}
}
由于 Incompatible types: Object is not convertible to T
错误,此代码无法编译。
如何在不进行反射的情况下正确地将 responseType
传递给 externalApi.get
和 return 正确的类型?
OP 可能已经猜到了,这本质上是不可能的。
如果 get
的调用站点可以做任何有用的事情来保留返回的类型 T
,那么它无论如何都会知道类型并可以提供正确的 class(提供这是通过调用站点传递传播的。
(另请注意,代码对 String
使用 ==
而不是 equals
或 switch
。)
我正在使用来自具有以下签名的外部 Maven 依赖项的 API:
public <T> T get(String key, Class<T> responseType)
API return 是一个 T
类型的对象,用于键值存储中的给定键。
在我的应用程序中有几种对象类型可以 returned,例如:Product
、Customer
等
我想将外部 API 包装到我的服务中,它将接收一个密钥并 return 找到的对象。我不知道如何从服务中 return 对象类型。以下是我的尝试:
public class MyService {
public <T> T get(String key, String objType) {
Class clazz = null;
if (objType == "Customer") {
clazz = Customer.class;
} else if (objType == "Product") {
clazz = Product.class;
}
return externalApi.get(key, clazz); // doesn't compile
}
}
由于 Incompatible types: Object is not convertible to T
错误,此代码无法编译。
如何在不进行反射的情况下正确地将 responseType
传递给 externalApi.get
和 return 正确的类型?
OP 可能已经猜到了,这本质上是不可能的。
如果 get
的调用站点可以做任何有用的事情来保留返回的类型 T
,那么它无论如何都会知道类型并可以提供正确的 class(提供这是通过调用站点传递传播的。
(另请注意,代码对 String
使用 ==
而不是 equals
或 switch
。)