由于scala语言本身是在jvm上,这一点比较容易。
以下是将要被调用的java代码:
点击(此处)折叠或打开
- package pkg1;
- public class Example1 {
- public String name;
- public int age;
- public float salary;
-
- public float getYearIncome(){
- return salary * 12;
- }
-
- public String getDescription(){
- String desc = "name : " + name + "\n"
- + "age : " + String.valueOf(age) + "\n"
- + "month salary : " + String.valueOf(salary);
- return desc;
- }
-
- public static void main(String[] args){
-
- }
- }
编译以后导出成jar包。
以下是调用以上java类的scala代码:
点击(此处)折叠或打开
- package JavaInteraction
- import pkg1.Example1
- object CallingExample {
- def main(args : Array[String]){
- val example = new Example1()
- example.age = 36
- example.salary = 7
- example.name = "Nonname"
- println("year income: " + example.getYearIncome() + "\n\n")
- println("description is: \n" + example.getDescription())
- }
- }
二、java代码里面调用scala的类
以下是示例的scala代码
点击(此处)折叠或打开
- package pkg1
- class Car {
- private[this] var year : Int = 0
- private[this] var miles : Int = 0
- def setYear(y : Int){
- year = y
- }
-
- def drive(distance: Int) {
- miles += distance
- }
-
- def getDistance() : Int = {
- miles
- }
- def getDescription() : String = {
- "year:" + year + " miles:" + miles
- }
-
- override def toString() : String = {
- println("-- entering function toString\n")
- "year:" + year + " miles:" + miles
- }
- }
java代码:
点击(此处)折叠或打开
- package CallingScala;
- import pkg1.Car;
- /*
- * XXX:注意一定要把scala的库,加载过来,不然scala类在java里面没法正常使用.
- * */
- public class Test {
- public static void main(String[] args){
- Car c = new Car();
- c.setYear(2);
-
- c.drive(100);
- c.drive(200);
-
- System.out.println("car description is: \n" + c.toString());
- //System.out.println("car description is: \n" + c.getDescription());
-
- }
- }
注意:
在java工程里面除了要导入刚才从scala工程导出的jar包以外,还要添加scala的库。
比如我在编译scala工程的时候,使用scala语言是2.10.4,那么,现在在java的工程里面也添加2.10.4版本的以下库:
scala-compiler.jar
scala-library.jar
scala-reflect.jar
(scala-swing.jar可以不添加)