blackdog
blackdog

Reputation: 2107

Can a native method call a private method?

I knew that in JAVA "native" is a special thing. It can do a lot of things. But I'm not able to read it right now. I don't know how to... I knew it can call an other mathod in JAVA. My question is: can it call a private method? if it is a YES, then only in the same class or any other classes? if it can call other's, then is it a problem that maybe it's dangerous? that is, it broke the rules. Where can I get more about the NATIVE? can anybody show me a link?

Upvotes: 12

Views: 8812

Answers (2)

Stephen C
Stephen C

Reputation: 719281

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.

Upvotes: 33

Jon Lin
Jon Lin

Reputation: 143916

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

Upvotes: 5

Related Questions