我想在方法调用中提供一个接口(interface)。根据给定的接口(interface),该方法应该创建一个实例。为此,我使用泛型为该方法提供不同类型的接口(interface)。这是一个例子:
static <T> T createClient(T, String endpointAddress) {
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean()
factory.setServiceClass(T.class)
factory.setAddress(endpointAddress)
(T) factory.create() // error -> java.lang.IllegalArgumentException: java.lang.Class is not an interface
}
// AccessibleClient is an interface. call method
createClient(AccessibleClient, "http://localhost/service")
我不知道我的方法是否是合适的解决方案。
最佳答案
你不能说T.class
——在Java中,该信息在运行时不可用。
根据 gontard的comment ,您可能想要这样的东西:
static <T> T createClient ( Class<T> t, String endpointAddress )
{
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass( t );
factory.setAddress( endpointAddress );
return (T) factory.create();
}
createClient( AccessibleClient.class, "...");
(另外,在 Java 中,您需要分号和 return
关键字 - 这是 Groovy 还是其他东西?)
关于java - 接口(interface)作为方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16012594/