IKVM 是一個強大的工具,能將 Java 位元碼轉換為 .NET 組件,讓 C# 專案直接引用 Java 類庫。本文記錄從環境搭建到跨語言調用的完整流程。
// SimpleReturnString.java
package com.helloikvm.simple;
public class SimpleReturnString {
public String returnString() {
return "Hello, IKVM!";
}
public void throwException() throws Exception {
throw new Exception("Hello, Exception!");
}
}
編譯並打包:
javac SimpleReturnString.java
jar cvf IKVM.jar com/helloikvm/simple/SimpleReturnString.class
使用 ikvmc 轉換為 .NET 組件:
ikvmc -out:IKVM.dll IKVM.jar
新建 C# 專案,添加以下 DLL 參考:
C# 調用代碼:
using com.helloikvm.simple;
namespace IKVMTest
{
public partial class Form1 : Form
{
private void btnTest_Click(object sender, EventArgs e)
{
SimpleReturnString simpler = new SimpleReturnString();
String returnString = simpler.returnString();
txtTest.Text = returnString;
}
}
}