什么是原生对象?

时间:2010-12-31 08:19:58

标签: java terminology

什么是本机对象意味着我发现java具有与本机对象接口的对等类?

2 个答案:

答案 0 :(得分:18)

Java程序可以使用JNI访问本机代码中实现的函数(编译为机器代码的任何内容)。与面向对象的本机代码接口需要一个java类,它使用jni将方法调用从java转发到本机类的实例。这个类是本机类的java对等。

一个例子: 我们需要在java程序中使用c ++中的print_hello类,为此我们需要在java中定义它的对等。

原生班级

  class print_hello{
  public:
      void do_stuff(){std::cout<<"hello"<<std::endl;}
  } 

java中的对等类

  class PrintHello{
    //Address of the native instance (the native object)
    long pointer;

    //ctor. calls native method to create
    //instance of print_hello
    PrintHello(){pointer = newNative();}

    ////////////////////////////
    //This whole class is for the following method
    //which provides access to the functionality 
    //of the native class
    public void doStuff(){do_stuff(pointer);}

    //Calls a jni wrapper for print_hello.do_stuff()
    //has to pass the address of the instance.
    //the native keyword keeps the compiler from 
    //complaining about the missing method body
    private native void do_stuff(long p);

    //
    //Methods for management of native resources.
    //

    //Native instance creation/destruction
    private native long newNative();
    private native deleteNative(long p);

    //Method for manual disposal of native resources
    public void dispose(){deleteNative(pointer);pointer = 0;}
  }

JNI代码(不完整)

声明为native的所有方法都需要本机jni实现。以下仅实现了上面声明的一个本机方法。

//the method name is generated by the javah tool
//and is required for jni to identify it.
void JNIEXPORT Java_PrintHello_do_stuff(JNIEnv* e,jobject i, jlong pointer){
    print_hello* printer = (print_hello*)pointer;
    printer->do_stuff();
} 

答案 1 :(得分:0)

如果Java对象具有用C编写的某些 native 方法,则它具有对等/本机对象。