Can a native method call a private method? - 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?

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.

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

Related

Does Java have regular-old functions?

What I mean is, does Java have functions that exist outside of classes that I can declare? (Like, before the main class)
This is something I can do in C++ and JS, etc.
Static method
Declaring a method to be static makes it non-object-oriented. Its scope is outside that of any instances of that class. Invoked via the class name, Person.doSomething rather than by an instance.
Often called a "class method" though that seems like something of a misnomer to my mind. That name suggests object-orientation where it does not exist. Java simply has no other place to store "just a function", so such functions are bolted onto a class. I think of them as orphaned code with no where else to live. Some folks consider this arrangement to be a poor design choice in Java, where an explicit holder of non-object-oriented code would have been better.
You can think of class methods as "just a function" since it is not behavior on an object.
Lambda
Java 8 and later supports lambda expressions, where you pass a chunk of executable in the same way we pass data. This is known as functional programming, distinct from object-oriented programming.
This is something like "just a function" but its scope includes elements inside its defining class.

How to make a member of a class to be accessible only in subclasses in any packages?

How to make a member of a class to be accessible only in subclasses in any packages? Protected is not a solution since it will open the member to other non subclasses classes.
Java does not provide absolute encapsulation. Some amount of discipline is required on the part of the programmer - both the original designer and anyone that uses a published API - to abide by some rules that are outside of the language. Regarding member access, you have identified one such case. What you want is not possible in Java.
Just to put this in broader perspective, I'd point out that even private members can be accessed by other classes if a programmer is willing to go far enough to do it. Calls made via JNI do not have to respect any of the access modifiers. See, e.g., Can a native method call a private method?
Other examples of out-of-language norms include the contract for equals/hashCode, which must be met for classes to behave well with respect to collections but is not enforced at the level of the language.
I understand why you want to do this; however, Java simply does not provide that capability.
You could do abstract class with protected member, and implement it in another packages. Consider you created some lib and design extensability for certain things. Later users of your lib will implement realizations of your class and has access to protected member and in same time not able to create implementation classes in your package. In example FilterReader class, it design for extensibility, after you implement it in somewhere in your code outside java.io package that protected fields and methods will be private to other classes in your package.
What you are trying to achieve ist not possible during to acces control:
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
You may rethink your software design, since yout problem is caused by architecture.
please be more specific in your question for getting further answer.
Solving your problem may cause sideeffects and is not in a OOD manner.
The only way to acces the private member is using an getter method with same visibilty issuses.

Visibility of Methods and their cost

I recently read this article by Jake Wharton. This is targeted at Android, but also perfectly valid for java I think.
Consider the following code:
public class A {
private String someField = "abc";
class B {
public void doSomething() {
System.out.println(someField);
}
}
}
We have a simple class A and an inner class B (This has a reference to A and can acccess its members). Class B is accessing the field someField in A even though it is private. According to the article, this is done by the compiler generating synthetic accessor methods which allow the inner class to access the field.
Now my way more basic question: Why does the compiler even care about visiblities when the code is compiled? As we have seen in this example, a new method is generated, which basically just introduces overhead.
Visibilities are a great thing for architecting good software, but if the compiler is done checking that everything is correct according to the declared visibilies, why not optimize those methods away (E.g. just taking everything for being public and allow calls to it)?
First I thought this was due to security reasons, but reflection allows the access of all fields, not caring for visibility as far as I know.
This might be a basic misunderstanding of me, if so, I would be happy if someone could explain it to me.
Why does the compiler even care about visiblities when the code is compiled?
The JVM doesn't allows access to private methods/constructors/fields outside a class. It has no special rule for nested classes which were added after this rule was designed. Instead the compiler adds accessor methods so the language can support a means of access the JVM doesn't.
As we have seen in this example, a new method is generated, which basically just introduces overhead.
Only if the method isn't called very much and isn't optimised.
Adding any simple method (On Hotspot, any method of 35 bytes or less) will be inlined very quickly and has no impact on performance (except if the maximum inline level is reached)
why not optimize those methods away
It does this at runtime so that previous rules continue to be enforced.
reflection allows the access of all fields, not caring for visibility as far as I know.
Though not by default, you have to explicitly want this as an option and not have a SecurityManager which prevents it.
If compiler converts all private fields to public fields in compile time, one problem will be happened when your project is compiled into library and reused by others. In that case, all your private fields will become public.
There are some tools for optimizing this. In Android, there is a tool named ProGuard that will convert all getter/setter to direct field access.

Inheritance of final class from the Java internals perspective

While declaring a class as final , we cannot Inheritance this class , my question is why ? - from the java internals perspective.
I assume that the same principle apply to methods and instance as well.
is it somehow related to the class loader as well ? who is actually stopping me from override it?
There's nothing related to the JVM or internals (not really sure what exaclty you mean by that), it's a compile issue simply because you're breaking the rules.
If I think myself as a Java compiler, after parsing the tokens in your code I'm just going to look around for logical errors (semantic analysis) e.g. a circular inheritance scheme. The moment I see someone's attempt at extending a final class, I'm gonna go bazooka. That's it. No need to wake up the big bosses, the JVM or any other internals because the program cannot be correctly compiled in the first place.
If you want to know how the compiler works the way it does internally, think that while the compiler parses your code, it creates and fills some structures internal to itself for the purpose of error-checking and bytecode-translation. Also imagine in a simplified scenario that the final keyword attached to a class just sets a field in one of these structures attached to your class. After syntactic analysis, the compiler goes on with "logical" (semantic) analysis and checks (among other things) if some lunatic tries extending a final class. Even a brute search in an inheritance graph can pull that off. If a class is final and still has children, halt and notify the lunatic. The issue won't get more internal than the compiler.
It is nothing to do with Java internals.
The purpose of declaring a class to be final it to prevent it from being subclassed.
My question was what happening "underground" while declaring final ...
Well ... when a class is declared as final a flag is set in the class file to say this. If you then attempt to load a class that purports to be a subclass of a final class, the classloader will throw a VerifyError exception. The checks are done in the ClassLoader.defineClass(...) methods ... which are also final, so that normal programs can't interfere with them.
This aspect of classfile verification needs to be watertight for Java security reasons. If it wasn't then you could probably cause mayhem in a Java security sandbox by tricking trusted code into using (say) a mutable subtype of String.
The Java compiler also checks that you don't extend a final class, but you could subvert that by (for example) creating ".class" files by hand. Hence the need for load-time checks ...
Who is actually stopping me from override it?
Actually, it is the classloader. See above.
Let's look at it elementally, When you declare a variable as final, you did that because you don't want the value of that variable be changed for any reason afterwards, Right?.
Okay, under the assumption that you agree to that. The same principle is also applicable to classes.
Let's look at it this way: Why will you ever want to inherit a class? Probably because you want get access to the properties of the class and her behaviors (methods), Right? Once you have inherited these properties and behaviors you have the right the modify the accessible behavior to suite your precise need without having to re-implement all other behaviors. This is the value and power of in inheritance.
Hence, declaring a class as final implies that you don't want anyone to modify any behavior of the class. You tries to state that who so ever that will want use your class should use it as IS.
Therefore, any attempt to modify a final class is illogical and should be considered as error.
Eg.
Imaging if someone should be able to inherit your final Authentication class and modifying the actual authentication behavior (method). This should be a security bridge as it might compromise your reasons for setting the class as final.
Hence, it is a design practice.
I hope that make some sense?

Reflection: Effective, Awesome, Necessary uses [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
What is reflection, and why is it useful?
So I've read the Reflection tutorial on Java's website, and I think I generally understand that it allows a class to inspect itself, having access to properties, methods, etc. However, how, if at all, does this relate to mutable or immutable code? Can classes change their own code using something like reflection? If not, what's the most awesome use of reflection you've come across/created?
Thanks!
No, reflection does not directly enable a class to change its code. However, there are some awesome things you can do with java.lang.reflect.Proxy - e.g. write generic code that implements any JavaBean-style interface (i.e. set and get methods), or even code that implements any interface by having all methods return default values - possibly even recursively, i.e. methods that return an interface type return an object that behaves in the same way.
This facility is used by Mock object libraries, and probably most prominently by the Groovy language to implement a fully dynamic language that supports duck typing and monkey patching.
Java reflection does not allow you to dynamically change the code of the program like you would be able to in a dynamic language such as ruby.
Java reflection allows you to see meta data regarding methods and properties of a class. It also allows you to call those methods or to change values of properties, without having prior knowledge of the methods and properties available.
To modify program code at runtime in Java, have a look at Aspect-Oriented Programming.
The most awesome use i've seen is in the JRuby bindings, to make Java classes dynamically available as ruby code. I've also used reflection myself to allow me look up error codes from a third party library that was using static int Constants instead of enums.

Categories