How to use Jar file in Golang?

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

How to use Jar file in Golang?

问题

在Go代码中使用JAR文件的类方法是否可能?如果可能的话,请给我提供相关链接。我在GoDoc/github.com/code.google上搜索了一下,但没有找到相应的包。

英文:

Is it possible to use jar file class methods in Go code. If so than please forward me the link for the same. I have searched the same in

> GoDoc/github.com/code.google

But there was no such package build.

答案1

得分: 28

在极端迂腐的意义上,你可以在Go中编写一种JVM环境,可以运行与Go分配的内存交互的JVM字节码。

从实际意义上讲,Java(以及Scala等)与Go的编译方式完全不同,这是不可行的。而且,Go有自己的运行时环境,这也使得从Java中运行Go函数变得复杂。

如果你需要从Go与Java代码进行通信,我建议你研究一下RPC(远程过程调用),你可以将Java程序作为一个独立的进程启动,并通过本地网络协作调用方法。这需要一些努力,但并不是很多。这肯定比编写一个真正从Go调用Java方法的框架要容易得多。

另一种选择是使用os/exec来调用Java程序,让它们输出到文件或命令行,然后读取输出并解析它,但这比RPC更加脆弱,容易出错并存在安全漏洞。

正如Evan在评论中提到的,你可以使用JNI(Java Native Interface)和C入口点。因此,使用Cgo可以启动JVM并调用Java代码。这个网站似乎有一个关于如何在C和C++中设置它的教程。我对从这个方向使用JNI不是很熟悉,所以无法真正推荐它或劝阻你使用它。不过,它确实会在构建过程中引入一个C依赖项,所以请注意这一点。

英文:

It's "possible" only in the extremely pedantic sense that you could theoretically write some sort of JVM environment in Go that can run JVM bytecode that happens to interact with memory allocated by Go.

In any practical sense, Java (and Scala etc) compile in completely different ways to Go and it's not feasible to do this. This is especially complicated by Go having its own runtime which complicates the inverse as well (running Go functions from Java).

If you need to communicate with Java code from Go, I advise looking into RPC, you can launch a Java program as a separate process and cooperatively call methods over your local network. This takes a little effort, but not very much. It's certainly easier than writing the framework to truly invoke Java methods from Go would be.

The other option is to invoke Java programs by using os/exec, having them output to a file or command line, and then reading in that output and parsing it, but that's a lot more fragile than RPC and prone to errors and security holes.

As Evan mentions in the comments, you can use the JNI (Java Native Interface) with a C entrypoint. So using Cgo you can launch the JVM and call Java code. This site seems to have a tutorial on how to set it up in C and C++. I'm not very familiar with using JNI from this direction so I can't really recommend it nor dissuade you from using it. It does introduce a C dependency into your build process though, so be aware of that.

答案2

得分: 2

我有一个类似的用例。我使用Kafka作为消息总线。生产者是用Scala编写的,消费者是一个Go应用程序。这个方案可以无缝地工作。最好的部分是,它可以在任何分布式环境中进行扩展。

英文:

I have a similar usecase. I use kafka as a message bus. The producer is in scala and consumer is a go application. This works seamlessly. Best part of this is, it can scale on any distributed setup.

huangapple
  • 本文由 发表于 2014年5月26日 22:24:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/23872323.html
匿名

发表评论

匿名网友

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

确定