Can reflection change the state of an object? - java

I read the following article about reflection in Java:
https://community.oracle.com/docs/DOC-983192
In it, the author describes how to change the values of an object's fields through reflection. He explains how to do it even if the field has private access.
I while back, I read Joshua Block's book: "Effective Java". There, he says that, in order to prevent unsafe access to an object's fields, methods, etc, whenever possible, we should give fields and methods the most restrictive modifier (ie. private whenever possible, public or protected if it is part of the exposed api).
My question is the following:
Why bother designing your classes to not expose sensible information if it can be accessed through reflection anyway?
(Actually, I am asking for the piece of information that I am missing to understand this topic)

For one thing, 'private' is not meant as a security feature. See this similar question. Java has a security system, which is what you should use if you really want that kind of protection.
'private' in OOP is a signal of intent and is part of the contract of your class. By marking a field as 'private', you are stating that if somebody sneaks in and modifies stuff with reflection or something, then all guarantees you make in the rest of your class are no longer valid.
It's kind of like the fine print in the warranty of your TV or other devices - if you start digging around inside the wiring (the private fields, so to speak), then the warranty is void and Samsung or whoever it is won't cover the cost of repairing whatever you may screw up while you're in there.

Related

Core OOPS : Encapsulation

Yesterday in an Interview I was asked
How Does Encapsulation works internally ?
I was really confused because as per me Encapsulation is simply
"The state of a class should only be accessed through its public interface."
but when it comes to internal working I ran out of words.So if anyone can explain that it would be so helpful.
I agree with commenters that asking for clarifications is a good idea - good questions can be even better than good answers, and allow you to ensure that you are actually answering what they think that they are asking.
In this case, I assume that they wanted you to explain how Java ensures that programmers do not violate encapsulation. This involves
built-in syntax and semantics for marking fields / methods as public, private, protected, or package-protected.
compiler checks to ensure that these are not violated
(external) tools available to detect code smells relating to encapsulation, such as calls to overridable methods from within a constructor.
(somewhat more far-fetched) no direct access to program memory, making, for example, reinterpret-casts such as found in C / C++ unavailable in Java; this also preserves encapsulation.
You could have ensured that this is what they wanted by asking "are you referring to how Java ensures that programmers do not violate encapsulation, that is, that they do not access the state of objects except through their public interface?"
Additional answers come to mind:
use of meaningful comments, easily accessible via JavaDoc both in-IDE and as browsable documentation, that allow programmers to understand how classes are meant to be used and composed.
strong coding conventions that enforce encapsulation, such as setting fields to the most restrictive access possible, and only making public those parts that should actually be public.

Java: Accessing private field via reflection (behaviour)

Junior in Java; using reflection is possible to access private fields (not asking how,
Question 1 and Question 2) Ok.
My questions are related with the nature of this behaviour.
Is there any limitation? Can I access any field of any .class I come across?
During my code, once you set the visibility of a field to lets say "public", is it changed forever or just up to the end of the context (method, if, for...)? Code below
Is it ok for everybody? I mean, Seniors programmers of StackOverflow, is it a security breach?
Code [EDITED]:
Field f = obj.getClass().getDeclaredField("field");
if (...) {
f.setAccessible(true);
// f IS accesible
}
// is f accesible?
Is there any limitation?
Yes - you need several JVM permissions (most notably accessDeclaredMembers and suppressAccessChecks, marked with big, bold warnings in the docs) for this to work; if your JVM's security profile is somewhat strict (say, the much-maligned applets), your code will not work because these permissions will not be available.
Does it get changed forever?
Yes, as long as your program keeps on running the fields will remain accessible (as long as you keep on using the same Field instance where you changed access permissions).
Is it bad?
Not necessarily. It allows java code to serialize and de-serialize objects with private fields, it allows complex mocking that may simplify testing, it allows you to peek into places you would not otherwise be able to peek into. However, since it breaks expectations, you should use it sparingly and make sure that users know that you require the extra permissions and "are looking under the hood". The docs (see above) state quite clearly that this is considered risky, and that it should only be allowed if you know what you are doing.

why we have to use private? in c++ and java?

why we use private keyword?i know it limits the access to a var or a method,but why we have to limit the access?
If you expose all of the methods and variables publicly, when another programmer tries to do something with a class you have written it will be really hard because he wont know which methods take care of the internal behavior of your class, which are the methods he is not supposed to use because he would mess up the internal state of the objects and cause a bug.
You don't "have to" do anything of the sort. It's just good practice to only expose that which absolutely must be exposed, especially when you're creating a large program where connections increase exponentially, and risk of side effects increase with it. It's really all about managing complexity. Read up on encapsulation and information hiding and how this helps reduce complexity in large systems. A good book is Grady Booch's Object-Oriented Design for more on this.
In OO world to achieve encapsulation it is very essential to understand the functionality or behavior of object you would like to expose and each access identifier plays important role in it.In Code Complete book McConnell strongly encourages making all variables private.
Consider you are building a utility library and you are going to expose methods to external world as utilities. But those methods may call few methods which are private. So calling those private methods directly may not make any sense and in worst case, they may even harm the state of the object too. There are lots of examples to explain the usage of private even in jdk.
In String class, there is a private method checkBounds which just checks for valid constructor arguments in case of public String(byte bytes[], int offset, int length, String charsetName)
Exposing this method (making it public) makes no sense for String class.
private as the name implies it is something which resides private/unaccessable from the outer class. Object Oriented Programming language has one important concept called Encapsulation which means to restrict the access to some of the object's components. While developing a code you need to hide some objects from the other class, in these case delete those object/variable as private. A private access is only to the class where is it defined.

In OOP, Private membes are private for who?

In OOP why need to put something Private , for example. I know that any private member can not be accessed but with the same class objects. But why I need to do that while I am the only coder of my project. The same question extends to Protected, protected from who!
private and protected are not there to prevent other coders from accessing the internals of a class, but (also) to prevent yourself from creating a program without clearly defined interfaces.
If every class in your project can modify every other class, you're not only prone to introduce bugs because of the huge state space, but also preventing yourself from:
Changing the implementation (while keeping the interface the same) of any class.
Ever introducing anyone not familiar with all the internals of all the classes to the project. Unless you have a perfect memory and can recite every line of code you've ever written, that includes future you.
Mocking up objects for unit testing
Interacting with other versions of your program/library. Suppose you do change internals of one class, and you manage to track down every reference to that internal property in your project. Even then, you may need to interface with the old version of your program again. This becomes especially hard if used properties instead of getter/setter methods.
Access modifiers achieve two different things:
They limit the amount of code that can cause side effects, making it easier to establish invariants.
They protect clients of the class from changes to the internal representation.
For small projects, these advantages might not be immediately visible, especially for beginners.
Protected from your future self, who could otherwise accidentally forget what parts of an object are a detail that should be decoupled from the rest of the system, and which parts are a solid interface that can be relied on by the rest of the system.
the language tries to force you, to write "good" code. "good" means that the code is structured, clean and not susceptible to error. so you have to declare types, private members and so on. if you don't want that, you could use a language thats lesser in this aspects, like python. but this means, that your program could (could!) be more insecure or if it gets very big, easy to misunderstand. it's the same as with comments. you haven't to write them. especially when you are the only programmer. but it's a good style and you will be very thankfull for that if you read your program again, in a half year.
You mark the members of a class private that must not be accessed from outside the class. E.g., you use it to hide implementation details, so you can change the implementation without affecting other code using your class. Hiding implementation details is one of the key aspects of OOP (encapsulation). If you create a Car class, and then you write a lot of code that uses the Car class, and you suddenly realize that your implementation performs very poorly and you need to refactor it, if all of the Car implementation details are private to the Car class, you know that none of the code using Car accesses those things and you can change them at will. If you didn't mark them private, you might have used some of them in that other code, which would then break.
Similarly, protected (in Java, anyway) is for the same purpose but allows classes derived from your class to access those members. This is fairly weak protection, because of course it means that you can't change the implementation details of the base class without affecting derived classes.
Think about it this way: The protection level defines what you can change later without care for any other piece of code besides this class (private), without care for any other piece of code besides this class and every class inheriting from this class (protected) and without care for any other piece of code besides every piece of code using this class (public).
private or protected come from encapsulation concept. and it comes from data hiding concept. I believe this intoduction is clear and useful at least for me :
Encapsulation is the process of combining data and functions into a
single unit called class. Using the method of encapsulation, the
programmer cannot directly access the data. Data is only accessible
through the functions existing inside the class. Data encapsulation
led to the important concept of data hiding. Data hiding is the
implementation details of a class that are hidden from the user. The
concept of restricted access led programmers to write specialized
functions or methods for performing the operations on hidden members
of the class. Attention must be paid to ensure that the class is
designed properly. (Sripriya Rajagopalan)
Note: Answers are well, and this answer is to complete them
If you define a member (variable or method) of a class as private, you won't be able to use it from outside, using another class, using the dot operator. Protected helps you to protect the member variable or method from being inherited.

What are the uses of getter/setters in Java? [duplicate]

This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 7 years ago.
I have seen member variables given a private modifier and then using getter/setter methods just to set and get the values of the variable (in the name of standardization).
Why not then make the variable public itself (Other than cases like spring framework which depends on getter/setters for IOC etc). It serves the purpose.
In C# I have seen getter/setter with Capitalization of the member variable. Why not make the variable public itself?
In order to get a stable API from the first shot. The Java gurus thought that if later on, you might want to have some extra logic when setting/getting an instance member, you don't want to break existing API by replacing public fields with public methods. This is the main reason in Java.
In the case of C#, public properties are used instead of public fields because of binary interface compatibility. Someone asked a similar question right here, on SO.
So, it's all about encapsulating some logic while still preserving interface for... future proofing.
Even back in 2003 it was known that getter and setter methods are evil.
Because interfaces only allow for specifying methods, not variables. Interfaces are the building stones of API's.
Hence, to access a field through an interface, you need to have the getter and setter.
This is done so you can change the getter or setter implementation in your public API after you release it. Using public fields, you wouldn't be able to check values for validity.
Encapsulation
You also mentioned C# properties. These are really just getters/setters under the hood, but with a more concise syntax.
It's part of encapsulation: abstracting a class's interface (the "getters" and "setters") from its implementation (using an instance variable). While you might decide to implement the behaviour through direct access to an instance variable today, you might want to do it differently tomorrow. Say you need to retrieve the value over the network instead of storing it locally—if you have encapsulated the behaviour, that's a trivial change. If other objects are relying on direct access to an instance variable, though, you're stuck.
The most and foremost use for getters and setters in Java is to annoy the developers. The second most important use is to clutter the code with useless noise. Additionally, it forces you to use a different name for the same thing, depending on where you are (inside or outside the class). Not to forget the added ambiguity (do you call the getter inside the class or do you use the field directly?) Next, they are used to allow access to private data but that's just a minor side effect ;)
In other programming languages, the compiler will generate them for you (unless, of course, you provide your own implementations). In Delphi, for example, you have read and write modifiers for fields (just like private, static or final in Java). The define if you'll have a getter or setter generated for you.
Unlike the Delphi guys, the Java guys wanted everything to be explicit. "If it's not in the source, it's not there". So the only solution was to force people to write all the getters and setters manually. Even worse, people have to use a different name for the same thing.
Getters and setters may very well be the greatest lie ever told. They are considered a sign of good design, while the opposite is true. New programmers should be taught proper encapsulation, not to write dumb data carrier classes that contain nothing but getters and setters.
(The idea that you need getters and setters to future-proof your code if you want to change the implementation later on is an obvious case of YAGNI. But that is really beside the point.)
The most common reason is a poor understanding of encapsulation. When the developer believes that encapsulating stuff really just means getters & setters rather than encapsulating behavour.
The valid reasons for having getters/setters are:
1) You are making a generic¹ object such as JComponent. By using a getter/setter rather than direct access to the variable means that you can do some pre-processing on said variable first (such as validate it is with a set range) or change the underlying implementation (switching from an int to a BigInteger without changing the public API).
2) Your DI framework does not support ctor injection. By having just a setter you can ensure that the variable is only set once.
3) (Ties in with #1) To allow tools to interact with your object. By using such a simple convention then GUI tools can easily get all the settings for a given component. An example of this would be the UI builder in NetBeans.
¹ Of the not-Generic type. Bad word to use I know, please suggest an alternative.
Having a setter allows you
perform validation
to fire a property changed event if the new value is different from the previous value
In the case in question there is no need for getter and setter if the value is simply read or written.
Well,
OOP. ;)
Or to be a little more precise:
Getters and Setters are used to provide a defined interface to a classes
properties. Check the OOP link, it describes the concepts more in detail...
K
You'd need encapsulate those attributes if there are constraints for example or to make general validity checks or post events on changes or whatever. The basic use is hiding the attribute from the "outer world".
Some Java frameworks require them (JavaBeans I think).
-- Edit
Some posters are trying to say this is about encapsulation. It isn't.
Encapsulation is about hiding the implementation details of your object, and exposing only relevant functions.
Providing a get/set that does nothing but set a value does not accomplish this at all, and the only reason for them is:
Perform some additional validation before set/get
Get the variable from somewhere else
Integrate with frameworks (EJB)
There are several reasons:
Some Java APIs rely on them (e.g. Servlet API);
making non-final variable public is considered to be a bad style;
further code support: if sometime in future you`ll need to perform some actions before each access/mutation (get/set) of the variable, you will have less problems with it.
In C# constructions like
public int Age
{
get
{
return (int)(today() - m_BirthDate);
}
}
are are just syntactic sugar.
property idea is core in OOP (Object oriented programming). But problem is that Java introduce them not in core of language (syntax / JVM), but (probably few years later??? historics of Java say better) as convention: pair of consistent getters/setter is property in bean, concept of property is in libraries, not in core.
This generate problem in few libraries, framework. Is single getter a read only property or not? That is the question. I.e.in JPA entities if You want implement classic method (algorithm) beggining with "get" like getCurrentTine() is the best mark by #Transient to disable interpretation like property having value.
In other words, I like very much property concept in C# designed 10 years later and better. BTW C# property has getter/setter too, but sometimes/partially hidden, visible at low level debugging. Free from question "why getter" etc ...
In Java world is interesting to read about Groovy concept of property (hidden getter/setter in different way than C#) http://www.groovy-lang.org/objectorientation.html#_fields_and_properties
EDIT: from real life, every java object has getClass() method, tools from java.beans.BeanInfo package report this as property "class", but this not true. It isn't property (readonly property) in full sense. I imagine properties like C# (with his internal hidden name get_Something1) hasn't conflict with "functional" GetSomething2()

Categories