[英]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.