在C#中調用Java代碼并處理多態,可以通過以下步驟實現:
首先,確保你已經將Java類庫添加到C#項目中。可以使用Java Native Interface (JNI)或者Java Native Access (JNA)來實現這一點。這里我們以JNI為例。
在Java中定義一個具有多態性的類。例如,我們定義一個Animal
類和一個Dog
類,Dog
類繼承自Animal
類:
// Animal.java
public class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
}
}
// Dog.java
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog barks");
}
}
javac
命令編譯Java類,并使用javah
命令生成JNI頭文件:javac Animal.java Dog.java
javah -jni Animal
DllImport
屬性導入Java類庫。然后,使用CSharpJavaClass
類加載Java類,并調用多態方法:using System;
using System.Runtime.InteropServices;
class Program
{
static void Main()
{
// 加載Java類庫
IntPtr javaLibrary = LoadJavaLibrary();
// 創建Java對象
IntPtr animalHandle = CreateJavaObject(javaLibrary, "Animal");
IntPtr dogHandle = CreateJavaObject(javaLibrary, "Dog");
// 調用多態方法
CallMethod(animalHandle, "makeSound"); // 輸出 "The animal makes a sound"
CallMethod(dogHandle, "makeSound"); // 輸出 "The dog barks"
// 釋放資源
ReleaseJavaObject(animalHandle);
ReleaseJavaObject(dogHandle);
FreeJavaLibrary(javaLibrary);
}
static IntPtr LoadJavaLibrary()
{
return NativeMethods.LoadLibrary("path/to/your/java_library.so");
}
static IntPtr CreateJavaObject(IntPtr library, string className)
{
return NativeMethods.CreateObject(library, className);
}
static void CallMethod(IntPtr objectHandle, string methodName)
{
NativeMethods.CallMethod(objectHandle, methodName);
}
static void ReleaseJavaObject(IntPtr objectHandle)
{
NativeMethods.ReleaseObject(objectHandle);
}
static void FreeJavaLibrary(IntPtr library)
{
NativeMethods.FreeLibrary(library);
}
}
public static class NativeMethods
{
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr CreateObject(IntPtr library, string className);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern void CallMethod(IntPtr objectHandle, string methodName);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern void ReleaseObject(IntPtr objectHandle);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool FreeLibrary(IntPtr hModule);
}
注意:請將path/to/your/java_library.so
替換為實際的Java類庫路徑。
通過以上步驟,你可以在C#中調用Java代碼并處理多態。