2011年5月2日 星期一

6. Scala 與 Java 之 static method 互相呼叫

1.在 Scala 中如何呼叫 Java 的 static method?

很簡單,與在 Java 中使用的方式一樣,「 class.method(param...) 」就可以呼叫到。
public class J1 {
  static public void static_m1() {
    System.out.println("J1.static_m1...");
  }
}
在 Scala 中的呼叫方式
class S1 {
  def print = {
    println("S1.print...");
    J1.static_m1  // 這裡呼叫 Java 的 static method
  }
}

2.在 Java 中如何呼叫 Scala 的 static method?

Scala 中沒有 static method,取而代之使用 object 來取代。
在 Java 需要使用 static method/field 時,若你改使用 Scala 撰寫,此時你需要 create 另一個同名的 object 來處理原來在 Java 中使用static method/field 的事情。
class S {
  def print_instance = println("S.instance")
}
object S {
  def print_static = println("S.static")
}

其中的 print_static 是原來在 Java 使用 static method 的部份。

那在 Java 中如何呼叫 object S 的 method?

做法為 「 class.method(param...) 」,與呼叫 Java 寫出來的 static method 一模一樣。
class J {
  void p() {
    S.print_static(); // 這裡呼叫 Scala 的 object S 的 method
  }
}

在 Scala 中同名的 class 與 object 會稱為 companion。上例中的 class S 是 object S 的 companion class,object S 是 class S 的 companion object。

object S 編譯之後,會產生一個 S$ 的 JVM class,也就是 Java 看到一個 S$ class。

「那為何 Java 使用 S.print_static(),可以呼叫到 object S 的 method?」

scalac 做了一些手腳,當定義 object 時, scalac 會在對應的 companion class中,插上所定義 object 中的所有 method,並且改為 static。當呼叫 companion class 中的 static method,會 forward 到 companion object 對應的 method。

讓我們看上例 scalac 所產生的 classfile 即可很清楚了解。


S$ 對應到 object S 的部份。



S 為原來 class S 的部份。
由上面可清楚看出, S 包含一個 print_static 的 method,該 method 本來定義在 object S 中,這裡被重新複製一次,並且標明為 static,所以 Java 使用 S.print_static 就可呼叫。

沒有留言:

張貼留言