[ Help | Solution | Course Notes | Exercises ]


Accessing Java Fields from Native Code

The Problem

In this exercise, you will access fields from a Java object. In addition to reading the values from the object, you will also change the values in the object from within native code.

Task list

  1. Task #1. Use javac to compile JavaFields.java and Main.java. These files are provided because the interesting part of the exercise is in implementing the native code.

  2. Task #2. Create the C/C++ header file JavaFields.h with javah.

  3. Task #3. Implement the native method manipulateFields in C++. The function won't take any arguments. Inside the function, you should retrieve the values of the four fields (i, f, si, pi) and print them. Then you should modify the values of these fields (the values you choose are not important.) Name this C++ file JavaFieldsImp.cpp (or JavaFields.C, depending on which extension your compiler accepts.) JavaFieldsImp.skel can be used as a starting point. (Expand comments of the form "//+".)

  4. Task #4. Compile the C++ file and create a shared library.

  5. Task #5. Test the program by running the Java interpreter.

Step-by-step

The above task numbers are linked to the help page. Also available is the complete solution of the exercise. With the solution, you will also find sample scripts to build and execute the program under Windows NT, Solaris and Linux.

Copyright © 1998 Sergio Antoy. All Rights Reserved
February 99, version 020199