Is it possible to call a native CPP function using JNI which takes generic arguments? Something like the following:
public static native <T, U, V> T foo(U u, V v);
And then call it like:
//class Foo, class Bar, class Baz are already defined;
Foo f = foo(new Bar(), new Baz());
Can anyone please provide me with a sample which is actually doing this or some tutorial on the net which does this? I am asking because in my CPP JNI function (called by JVM), I get unsatisfied link error.
CPP Code follows:
JNIEXPORT jobject JNICALL Java_Processor_process (JNIEnv *env, jclass processor_class, jobject obj1, jobject obj2)
{
jclass bar_class = env->FindClass("Bar");
jmethodID getFooMethod = env->GetMethodID(bar_class, "getFoo", "()Ljava/lang/Object;");
//getFoo() is defined as `public Foo getFoo();` in Bar.java
return env->CallObjectMethod(obj1, getFooMethod);
}
EDIT:
I have tried by modifying the code but now I am getting NoSuchMethodError:
Java code:
public static native <U, V> String foo(U u, V v);
//...
String str = foo(new Bar(), new Baz());
CPP code:
JNIEXPORT jstring JNICALL Java_Processor_process (JNIEnv *env, jclass processor_class, jobject obj1, jobject obj2)
{
jclass bar_class = env->FindClass("Bar");
jmethodID getFooMethod = env->GetMethodID(bar_class, "getFoo", "()Ljava/lang/String;");
//getFoo() is now defined as `public String getFoo();` in Bar.java
return env->CallObjectMethod(obj1, getFooMethod);
}
Does this mean that JNI has no support for generics or am I missing something?
There are numerous questions regarding type erasure on stack overflow (e.g. Get generic type of java.util.List), what you’re looking to do is neither possible with JNI nor Java itself. The runtime type signature of foo is (in both worlds, or actually, there is only one world)
Object foo(Object u, Object v), which will do an implicit class cast on the return value to whatever type you call it with.As you might notice (and as mentioned in the comment to your question), there’s no way for you to know what type
Tis.EDIT:
By the way, the getFoo method is supposed to return ‘Foo’, so shouldn’t you be doing
Come to think of it, your entire call sequence seems out of place… you’ve got a
foowhich is native, returning string. Nowfoolooks forgetFooinBar, which returns ‘Foo’, and returns the result of that call directly, effectively trying to return aFoo(Foo getFoo()according to the comment) where string is expected.