Q
傳遞類的功能
0
A
回答
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")
相關問題
- 1. 傳遞類屬性的功能
- 2. 傳遞XAML窗口類型的功能
- 3. 傳遞自(功能)
- 4. 將mysqli傳遞給功能使用類
- 5. 傳遞載體的功能
- 6. 傳遞價值的功能
- 7. jQuery的不傳遞功能
- 8. 傳遞$(本)的功能
- 9. 傳遞用Cython功能用Cython功能
- 10. 傳遞矩陣功能,C
- 11. 傳遞到座功能
- 12. 傳遞給JS功能
- 13. 傳遞懶功能參數
- 14. 功能 - 傳遞參數。
- 15. 傳遞價值JS功能
- 16. 傳遞變量名功能
- 17. 傳遞片任意功能
- 18. 傳遞數組到功能
- 19. 傳遞事件到功能?
- 20. 傳遞/返回類型參數類的功能
- 21. 傳遞一個功能到另一個功能相同的類內
- 22. jQuery的傳遞$(本)的功能
- 23. 傳遞的unique_ptr <int[]>的功能
- 24. 傳遞的std ::矢量爲任何類型的功能
- 25. 傳遞派生類的列表的功能在C++
- 26. 傳遞多頭排列的JSNI功能
- 27. 傳遞當前項目的功能
- 28. jQuery的傳遞$這功能參數
- 29. 傳遞動態數組的功能
- 30. 傳遞字符串VAR的功能
是任何回答適合接受的? – dmahapatro