Can a native method call a private method?
You can call private methods on a Java object that's passed to a native method via the JNI interface. It's not the same thing as within Java, calling methods on other Java objects. You have to be very careful because JNI does not enforce class, field, and method access control restrictions that are expressed through the use of modifiers such as private
and final
. So it can be dangerous. For example, native code can modify a final
constant field of a class, after the JIT compiler has inlined it.
Here's the relevant section of the JNI docs concerning functions and pointers: http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/design.html#wp16696
The JNI Programmer's Guide and Specification says this in "10.9 Violating Access Control Rules":
"The JNI does not enforce class, field, and method access control restrictions that can be expressed at the Java programming language level through the use of modifiers such as private and final. It is possible to write native code to access or modify fields of an object even though doing so at the Java programming language level would lead to an
IllegalAccessException
. JNI's permissiveness was a conscious design decision, given that native code can access and modify any memory location in the heap anyway."
So the answers to your questions are:
Can it call a private method?
Yes.
if it is a YES, then only in the same class or any other classes?
Any class.
if it can call other's, then is it a problem that maybe it's dangerous? that is, it broke the rules.
The designers' rationale for not attempting to enforce the normal Java access rules is clearly stated in the text quoted above. Yes it is potentially dangerous, but any use of JNI is potentially dangerous.