[英]Possibility to call a Java static method in Kotlin
Suppose we have a Java static method: 假设我们有一个Java静态方法:
//Java code
public static void printFoo() {
System.out.println("foo");
}
It is possible to call that method in Kotlin? 可以在Kotlin中调用该方法吗?
Yes, you can. 是的你可以。 Java code:
Java代码:
public class MyJavaClass {
public static void printFoo() {
System.out.println("foo");
}
}
Kotlin code: Kotlin代码:
fun main(args: Array<String>) {
MyJavaClass.printFoo()
}
So easy =) 这么容易=)
Yes . 是的 It's documented in the Java Interop
它在Java Interop中有记录
http://kotlinlang.org/docs/reference/java-interop.html http://kotlinlang.org/docs/reference/java-interop.html
The docs show the following example 文档显示以下示例
if (Character.isLetter(a)) {
// ...
}
The only caveat I see is that they can't be passed around with an instance and accessed on instances of the class like you can in Java but this is usually considered bad practice anyway. 我看到的唯一警告是,它们不能与实例一起传递,并且像在Java中一样可以在类的实例上访问,但这通常被认为是不好的做法。
The answer from 0wl is generally correct. 0wl的答案通常是正确的。
I just wanted to add that some of the Java classes are mapped to special Kotlin classes. 我只是想补充说一些Java类被映射到特殊的Kotlin类。 In this case you must fully qualify the Java class for this to work.
在这种情况下,您必须完全限定Java类才能使其正常工作。
Example: 例:
fun main(args: Array<String>) {
println(java.lang.Long.toHexString(123))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.