Next: , Previous: Arrays, Up: About CNI

12.11 Methods

Java methods are mapped directly into C++ methods. The header files generated by gcjh include the appropriate method definitions. Basically, the generated methods have the same names and corresponding types as the Java methods, and are called in the natural manner.

12.11.1 Overloading

Both Java and C++ provide method overloading, where multiple methods in a class have the same name, and the correct one is chosen (at compile time) depending on the argument types. The rules for choosing the correct method are (as expected) more complicated in C++ than in Java, but given a set of overloaded methods generated by gcjh the C++ compiler will choose the expected one.

Common assemblers and linkers are not aware of C++ overloading, so the standard implementation strategy is to encode the parameter types of a method into its assembly-level name. This encoding is called mangling, and the encoded name is the mangled name. The same mechanism is used to implement Java overloading. For C++/Java interoperability, it is important that both the Java and C++ compilers use the same encoding scheme.

12.11.2 Static methods

Static Java methods are invoked in CNI using the standard C++ syntax, using the :: operator rather than the . operator.

For example:

     jint i = java::lang::Math::round((jfloat) 2.3);

C++ method definition syntax is used to define a static native method. For example:

     #include <java/lang/Integer>
     java::lang::Integer::getInteger(jstring str)

12.11.3 Object Constructors

Constructors are called implicitly as part of object allocation using the new operator.

For example:

     java::lang::Integer *x = new java::lang::Integer(234);

Java does not allow a constructor to be a native method. This limitation can be coded round however because a constructor can call a native method.

12.11.4 Instance methods

Calling a Java instance method from a C++ CNI method is done using the standard C++ syntax, e.g.:

     // First create the Java object.
     java::lang::Integer *x = new java::lang::Integer(234);
     // Now call a method.
     jint prim_value = x->intValue();
     if (x->longValue == 0)

Defining a Java native instance method is also done the natural way:

     #include <java/lang/Integer.h>
       return (jdouble) value;

12.11.5 Interface methods

In Java you can call a method using an interface reference. This is supported, but not completely. See Interfaces.