Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a native method call a private method?

Tags:

java

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?

like image 814
blackdog Avatar asked Aug 31 '12 03:08

blackdog


People also ask

Can private methods be called?

We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private method of different class we will use Reflection API.

Can an object call a private method?

Object users can't use private methods directly. The main reason to do this is to have internal methods that make a job easier.

Can a private method call a public method?

If a private method must call a public method, then the content of the public method should be taken and placed in a private method, which both methods can then call.

Can you call a private method from a subclass?

In Java, you cannot directly access a private method from outside the class, that is you cannot invoke the private method by its name.


1 Answers

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.

like image 169
Stephen C Avatar answered Nov 16 '22 01:11

Stephen C