[英]How can I pass the class of my parameter to another method call?
我正在创建一个方法,该方法将对JAXRSClientFactory
进行调用,如下所示。
public T create(Class<T> resourceType) throws Exception {
Class<T> resource = JAXRSClientFactory.create(basePath, resourceType.getClass(), username, password, null);
// do common configuration for any interface T
Client client = WebClient.client(resource);
WebClient webClient = WebClient.fromClient(client);
SSLUtil.configure(webClient);
return resource.newInstance();
}
但是,这不符合我的预期,因为resourceType.getClass()
返回java.lang.Class
而不是T
的类。
JAXRSClientFactory
的调用更改为使用resourceType
会导致以下不兼容的类型错误:
如何修改此方法,以便可以将T
类传递给JAXRSClientFactory.create()
?
看一下JAXRSClientFactory#create(String,Class,String,String,String) :
参数:
baseAddress
-baseAddress
cls
代理类,如果没有接口,则将创建CGLIB代理
username
-用户名
password
-密码
configLocation
配置资源的类路径位置返回:
类型代理
您修改的代码:
public T create(Class<T> resourceType) throws Exception {
T resource = JAXRSClientFactory.create(basePath, resourceType, username, password, null);
Client client = WebClient.client(resource);
WebClient webClient = WebClient.fromClient(client);
SSLUtil.configure(webClient);
return resource;
}
resourceType.getClass()
将始终返回Class<Class>
结果,而不是<Class<T>
。
由于您已经具有Class<T>
作为参数,因此您可能应该这样做:
T resource = JAXRSClientFactory.create(basePath, resourceType, username, password, null);
您似乎在印象中,参数Class<T> resourceType
是Class<T> resourceType
的实例。这是错误的。
的参数定义Class<T> resourceType
没有定义resourceType
作为的一个实例T
,但作为类的T
(即,实例Class
是T.class
)。
因此,由于resourceType
是类的实例,因此调用resourceType.getClass()
返回Class.class
。
如果要将参数作为T的实例,则需要方法签名为:
public T create(T resourceType)
但是实际上,我怀疑您可能确实想要Class而不是实例,因此您应该JAXRSClientFactory.create
的调用JAXRSClientFactory.create
为:
T resource = JAXRSClientFactory.create(basePath, resourceType, username, password, null);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.