2017-08-11 24 views
3

我有一個接受Class參數的Java方法。我需要通過Integer.class,但從Kotlin代碼。我試過Int::class.java,但是這不起作用,因爲int.class被傳遞給函數。我的問題是,如何從Kotlin訪問Integer.class從Kotlin訪問Integer.class

的Java

void foo(Class clazz); 

科特林

foo(Int::class.java) // does not work, int.class gets passed to foo 

回答

7

必須使用KClass#javaObjectType拿到包裝類型類科特林:

返回一個Java Class斯塔nce對應於給定的KClass實例。在基元類型的情況下,它返回相應的包裝類。

例如:

//     v--- java.lang.Integer 
println(Int::class.javaObjectType) 

//     v--- int 
println(Int::class.java) 
+0

對於更多的細節可以參見[這裏](https://stackoverflow.com/questions/45397859/whats-the-behavior-of-iterableall-why-的確,科特林-charclass將-java的字符-JA/45400025#45400025)。 –

相關問題