如何在不为每个调用启动JVM的情况下,从Go中调用Java代码?

huangapple go评论109阅读模式
英文:

How to call java code from Go without invoking the JVM for every call?

问题

在Go语言中,可以调用Java代码吗?如果可以,有没有推荐的方法?是否可以在每次函数调用时都不需要启动JVM?

也就是说,是否有类似于Python中的jpype解决方案,可以在启动JVM后,只需启动一次,然后导入Java类并调用它们?

英文:

Is it possible (and if so, what is the recommended way) to call java code from Go, without the need to start the JVM for every function call?

I.e, is there any equivalent to the jpype solution for python, which lets you start the JVM once, and then import java classes and call them, using the already started up JVM?

答案1

得分: 7

使用cgo调用C代码,该C代码使用JNI调用API创建JVM实例,并使用JNI接口调用Java代码。由于goroutine在技术上可以在本机线程之间切换,因此在进入和退出Go代码时,您可能需要非常小心地测试、附加和分离线程到JVM,并且可能需要使用类似pthreads的本机线程库进行补充。

英文:

Use cgo to call into C code that creates a JVM instance using the JNI invocation API, and call into Java code using the JNI interface. As goroutines can technically switch between native threads, you'll probably have to be very careful about testing, attaching and detaching threads to the JVM upon entry and exit from Go code and/or supplement with use of a native threads library like pthreads.

答案2

得分: 4

将你的Java代码打包成一个“服务器”,并使用RPC(如“rest/soap/thrift”)进行调用,并保持服务器运行。虽然我不知道有任何可以自动化这个过程的系统。

英文:

Bundle your java code in a "server" and call it with RPC like "rest/soap/thrift" and keep the server running. I don't know of any system that automate this for you though.

答案3

得分: 0

你可以在Java中创建一个Java管理类,该类能够与你的Go程序进行通信。你只需要运行这个类一次,当你的Go程序需要时,它会进行适当的调用其他Java代码的操作。

英文:

You can make a Java management class in Java which is capable of talking to your Go program, and which you run once and will make the appropriate calls to other Java code when your Go program asks for them.

huangapple
  • 本文由 发表于 2013年12月10日 01:41:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/20477037.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定