需要使用C#/ Xamarin来使用Java库。
爪哇
class MyObject{
private final string1;
private final Date date;
public MyObject(final String string1, final Date date){
//init here
}
}
在生成的.cs文件中......
namespace Com.MyPackage{
internal MyObject(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer){}
static IntPtr id_getString1;
public unsafe string String1{
[Register ("getString1", "()Ljava/lang/String;", "GetString1Handler")]
get{
if(id_getString1 == IntPtr.Zero){
id_getString1 = JNIEnv.GetMethodID(class_ref, "getString1", "()Ljava/lang/String;");
try{
return JNIEnv.GetString(JNIEnv.CallObjectMethod(((global::Java.Lang.Object) this).Handle, id_getString1), JniHandleOwnership.TransferLocalRef);
}finally{
}
}
}
}
//...
}
好的,所以它是内部的。所以我创建了一个新方法并将其更改为:
namespace Com.MyPackage{
public MyObject(Java.Lang.String string1, Java.Util.Date dateIntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer){
String1 = string1; //error
}
static IntPtr id_getString1;
public unsafe string String1{
[Register ("getString1", "()Ljava/lang/String;", "GetString1Handler")]
get{
if(id_getString1 == IntPtr.Zero){
id_getString1 = JNIEnv.GetMethodID(class_ref, "getString1", "()Ljava/lang/String;");
try{
return JNIEnv.GetString(JNIEnv.CallObjectMethod(((global::Java.Lang.Object) this).Handle, id_getString1), JniHandleOwnership.TransferLocalRef);
}finally{
}
}
}
}
//...
}
这会导致错误
属性或索引器' MyObject.String1'无法分配 - 它是只读的
这就是我试图在C#中获取新实例的方法。
IntPtr Map_Class = JNIEnv.FindClass("com/myPackage/MyObject");
IntPtr Map_defCtor = JNIEnv.GetMethodID(Map_Class, "<init>", "(Java.Lang.String, Java.Util.Date)V");
IntPtr ptr = JNIEnv.NewObject(Map_Class, Map_defCtor);
MyObject myObject = new MyObject("hello world", new Java.Util.Date(123),
ptr, JniHandleOwnership.TransferLocalRef
).JavaCast<MyObject>();