I am working with JNI and I have to pass in some generic types to the C++. I am stuck with how to approach this on the C++ side
HashMap<String, Double[]> data1 ;
ArrayList<ArrayList<String>> disc ;
I am new to JNI and looked around but could not find much help. Can some one help me how to write JNI code for this please. Any reference to material on the net would be very helpful too.
Short answer: You cannot.
Long answer: Type Erasure : http://download.oracle.com/javase/tutorial/java/generics/erasure.html
Consider a parametrized instance of ArrayList<Integer>
. At compile time, the compiler checks that you are not putting anything but things compatible to Integer
in the array list instance.
However, also at compile time (and after syntactic checking), the compiler strips the type parameter, rendering ArrayList<Integer>
into Arraylist<?>
which is equivalent to ArrayList<Object>
or simply ArrayList
(as in pre JDK 5 times.)
The later form is what JNI expects (because of historical reasons as well as due to the way generics are implemented in Java... again, type erasure.)
Remember, an ArrayList<Integer>
is-a ArrayList
. So you can pass an ArrayList<Integer>
to JNI wherever it expects an ArrayList
. The opposite is not necessarily true as you might get something out of JNI that is not upwards compatible with your nicely parametrized generics.
At this point, you are crossing a barrier between a typed, parametrized domain (your generics) and an untyped one (JNI). You have to encapsulate that barrier pretty nicely, and you have to add glue code and error checking/error handling code to detect when/if things don't convert well.
The runtime signature is just plain HashMap
and ArrayList
- Generics are a compile-time thing.
You can use javah
to generate a C header file with correct signatures for native functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With