繁体   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