简体   繁体   中英

How to execute scala code using java

I am new to scala . I have a requirement to execute the scala class using java.

My exact requirement is: I need to pass the entire scala class (file) as an argument to the java jar . That jar should read the scala code and execute it. I have searched many sites but did not find the appropriate answer. Is there any way to do the same?

Thank you in Advance.

Besides of your motivation to do that, it is for sure possible (I did it using my IDE - sbt project) I just made scala class as below:

import com.google.common.base.Objects

class Car(_color: String, _valid: Boolean) {
  val color: String = _color
  val valid: Boolean = _valid

  override def toString = Objects.toStringHelper(this).add("color",color).add("valid", valid).toString
}

After that I made class with main method to test it.

public class Test {
     public static void main(String[] args) {
        Car test = new Car("test", true);
        System.out.println("test = " + test);
    }
}

It compiled without any problems and the result was like below:

test = Car{color=test, valid=true}

Scala has its own compiler scalac whereas java uses javac . Since scalac compiles to class file that java can read and assuming that you are only using java libraries in the class then you can load the class in java. So what you need is to call scalac to compile the scala file and then load the generate class file using ClassLoader

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM