The Cygnus Native Interface for C++/Java Integration | ||
---|---|---|
Prev | The Cygnus Native Interface for C++/Java Integration | Next |
The only global names in Java are class names, and packages. A package can contain zero or more classes, and also zero or more sub-packages. Every class belongs to either an unnamed package or a package that has a hierarchical and globally unique name.
A Java package is mapped to a C++ namespace. The Java class java.lang.String is in the package java.lang, which is a sub-package of java. The C++ equivalent is the class java::lang::String, which is in the namespace java::lang, which is in the namespace java.
Here is how you could express this:
// Declare the class(es), possibly in a header file: namespace java { namespace lang { class Object; class String; ... } } class java::lang::String : public java::lang::Object { ... };
The gcjh tool automatically generates the necessary namespace declarations.
It is not that long since g++ got complete namespace support, and it was very recent (end of February 1999) that libgcj was changed to uses namespaces. Releases before then used nested classes, which are the C++ equivalent of Java inner classes. They provide similar (though less convenient) functionality. The old syntax is:
class java { class lang { class Object; class String; }; };The obvious difference is the use of class instead of namespace. The more important difference is that all the members of a nested class have to be declared inside the parent class definition, while namespaces can be defined in multiple places in the source. This is more convenient, since it corresponds more closely to how Java packages are defined. The main difference is in the declarations; the syntax for using a nested class is the same as with namespaces:
class java::lang::String : public java::lang::Object { ... }Note that the generated code (including name mangling) using nested classes is the same as that using namespaces.
Having to always type the fully-qualified class name is verbose. It also makes it more difficult to change the package containing a class. The Java package declaration specifies that the following class declarations are in the named package, without having to explicitly name the full package qualifiers. The package declaration can be followed by zero or more import declarations, which allows either a single class or all the classes in a package to be named by a simple identifier. C++ provides something similar with the using declaration and directive.
A Java simple-type-import declaration:
import PackageName.TypeName;allows using TypeName as a shorthand for PackageName.TypeName. The C++ (more-or-less) equivalent is a using-declaration:
using PackageName::TypeName;
A Java import-on-demand declaration:
import PackageName.*;allows using TypeName as a shorthand for PackageName.TypeName The C++ (more-or-less) equivalent is a using-directive:
using namespace PackageName;