Michael Mrozek
Michael Mrozek

Reputation: 175355

Accessing the outer instance of a nested class using JNI

In Java, I have an inner class that has a native method:

public class A {
    class B {
        public native void foo();
    }
}

The native method is implemented in JNI:

JNIEXPORT void JNICALL A_0024B_foo(JNIEnv* env, jobject b);

Obviously the native function has access to B.this; it was passed in as b. How do I get access to A.this, the enclosing outer instance of A?

Upvotes: 3

Views: 1370

Answers (2)

benkc
benkc

Reputation: 3382

Using javap, I'm pretty sure the answer is this$0

$ javac A.java
$ javap -s -p 'A$B'
Compiled from "A.java"
class A$B extends java.lang.Object{
final A this$0;
  Signature: LA;
A$B(A);
  Signature: (LA;)V
public native void foo();
  Signature: ()V
}

Note that if running on a unix-style command line you need the quotes to keep the $ from being interpreted as the start of a shell variable.

Also note (in case this comes up in someone else's search results) that the constructor for the inner class has an implicit first parameter of the outer class -- so if you want to construct one of these from native, you'll have to ask for the constructor that way.

Upvotes: 2

daveb
daveb

Reputation: 76171

Well, if there is no jni support to access $this or whatever the variable is actually called, you could just pass B.this to the native function.

Upvotes: 0

Related Questions