2013-08-02 117 views
0

我想要做類似下面的(簡單的例子):傳遞類的功能

f(Class t, x) { x as t } 

int x = f(int, "42") 

如何在Groovy做到這一點?

+0

是任何回答適合接受的? – dmahapatro

回答

3

一個更巧妙的方式將是使用封閉:

f = {Class t, x -> x.asType(t)} 

assert f(int, "2") == 2 
assert f(float, "2") == 2.0f 
assert f(double, "2") == 2.0d 
assert f(Integer, "2") == 2 
assert f(Long, "2") == 2L 
assert f(BigDecimal, "2") == 2G 
3

假設你定義˚F作爲一個類的方法,你可以這樣做:

class F 
{ 
    static <T> T f(Class<T> outputClass, input) 
    { 
     input.asType(outputClass) 
    } 
} 

然後使用它通過調用

F.f(Integer, "42") 

如果你不關心泛型(儘管他們也應該幫助你的IDE拿起返回值是T型的),這也是有效的:

class F 
{ 
    static f(Class outputClass, input) 
    { 
     input.asType(outputClass) 
    } 
} 

assert F.f(Integer, "42").class == Integer 
1

只是爲了完成你的代碼示例:

def f(Class t, x) { x.asType(t) } 

int x = f(int, "42")