簡體   English   中英

如何將參數的類傳遞給另一個方法調用?

[英]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> resourceTypeClass<T> resourceType的實例。這是錯誤的。

的參數定義Class<T> resourceType 沒有定義resourceType作為的一個實例T ,但作為類的T (即,實例ClassT.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM