在scala文件中包含java源 [英] Include java source in scala file

查看:196
本文介绍了在scala文件中包含java源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

包含java和scala代码的编译文件

我知道Scala可以很容易地使用Java类。但是,是否可以将Java源包含在scala文件中,并以任何方式使用scalac编译?

I'm aware that Scala can easily use Java classes. However, is it possible to include Java source inside a scala file and have it compile with scalac, in any way?

或者,是否可以在源代码中包含javac编译的字节码作为bytearray,并从中导入(yuck,yes)?

Alternatively, is it possible to include javac-compiled bytecode as a bytearray in the source, and import from it (yuck, yes)?

这是为作业,所以,不,我不能有单独的文件,它必须编译 scalac file.scala ,没有其他参数。

This is for homework, so, no, I can't have separate files, and it must compile with scalac file.scala, with no additional arguments. To clarify, this is a hard requisite by my teacher

推荐答案

我只是写了一个简单的例子

I just wrote a simple example

说你有一个类似这样的java类

say you have a java class like this

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("hello world");
    }
}

然后你写一些scala代码,字节数组

Then you write some scala code to turn that into a byte array

import java.io.{FileInputStream, FileOutputStream}
import collection.mutable.ArrayBuffer

val in = new FileInputStream("HelloWorld.class")
val out = new FileOutputStream("HelloWorldBytes.scala")

Console.withOut(out) {
  var data = in.read()
  print("val helloWorldBytes = Array[Byte](")
  print(if(data < 128) data else data - 256)
  data = in.read()
  while(data >= 0) {
    print(", ")
    print(if(data < 128) data else data - 256)
    data = in.read()
  }
  println(")")
}


in.close()
out.close()

然后你可以这样使用

val helloWorldBytes = Array[Byte](...)

object Loader extends ClassLoader {
  override
  def findClass(name: String): Class[_] =
    if(name == "HelloWorld") defineClass(name, helloWorldBytes, 0, helloWorldBytes.size)
    else super.findClass(name)
}

val helloWorld = Loader.loadClass("HelloWorld")
helloWorld.getDeclaredMethod("main", classOf[Array[String]]).invoke(null,null)

这篇关于在scala文件中包含java源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆