2013-04-15 64 views
1

我想在方法调用中提供一个接口。取决于给定的接口,该方法应该创建一个实例。为此我使用泛型为该方法提供不同类型的接口。这里的一个例子:接口作为方法参数

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") 

我不知道我的方法是适当的解决方案。

+1

不该“它是'createClient(T参数,字符串endpointAddress)'? – sanbhat

+0

您如何期望从界面创建实例? – Apurv

+2

它应该是'createClient(AccessibleClient.class,“http:// localhost/service”)' – gontard

回答

1

你不能说T.class - 在Java中,信息在运行时不可用。

gontardcomment,你可能想是这样的:(?此外,在Java中,你需要分号和return关键字 - 这是Groovy的或某事)

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, "..."); 

+0

我忘了提及我使用groovy而不是普通的java。在groovy中,这个信息在运行时非常好用,你不需要使用分号和返回。我接受你的答案,因为在Java的背景下,这是正确的。 – hitty5