recipe № 020

Accessing fields of object passed as argument

In this sample I will show you how to access fields of object passed as argument to native method.

We will use three Java classes: PassObject – it will call native methods, CustomClass – class with some fields, OtherClass – class that has some fields and is part of CustomClass.

Structure of the project is quite simple

We need two JavaBean classes (I will not put getters and setters here so I don’t bloat the code with lots of LOCs. All the fields are public, but you can do better here.

We will also need class that calls native method

As you can see, we are passing cc as method parameter. I need to access all the components later inside C code. Most of the work will be done there. The most interesting calls are related to retrieving ids of the fields and getting values from them

You can see “I” passed as last parameter to GetFieldID method. That’s type description. For all primitive types you can use one of the values from the table below

once you have field’s id, simply use one of Get{TYPE}Field methods to retrieve the value of the field.

As for the OtherClass, it’s very similar. The only difference is that you have get the class first.

Note the “LrecipeNo020/OtherClass;” that is class description in JNI. For details, take a look here:

If you want to run this sample, simply execute following commands