Search code examples
c++compiler-errorsjava-native-interfaceassignment-operator

Using assignment operator overloading to return jobject from class


I am using the JNI invocation API and I would like to be able to perform the following assignment in my main() function:

jobject Myjobject = MyClassInstance;

Where MyClassInstance is an object instance of MyClass.

MyClass.h:

// DEFINE OVERLOADED = OPERATOR //
    jobject operator= (const MyClass &);

MyClass.cpp:

jobject MyClass::operator =(const MyClass & MyInstance)
{
    return MyInstance.jobjectMember;
}

Where jobjectMember is a private jobject member of MyClass.

However, I keep getting the following error during compilation:

error: cannot convert ‘MyClass’ to ‘jobject {aka _jobject*}’ in assignment

Where am I going wrong?


Solution

  • In order jobject Myjobject = MyClassInstance; (which is initialization, not an assignment) to work you need to define a corresponding constructor for jobject class.

    class jobject
    {
        public: explicit
        jobject(MyClass const & that) {...}
    

    or define conversion operator for MyClass

      class MyClass 
      {
          public: explicit
          operator jobject const &(void) const
          {
              return this->jobjectMember;
          }
    
      jobject Myjobject{static_cast<jobject const &>(MyClassInstance)};