Protecting internal class variable in jar - java

We have a getter method within a class.
Within the same JAR we want the variable to be accessible with the no-identifier access level, from the same package and subpackages.
Below the access levels from: http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Our problem is, how do we stop someone from taking the compiled .JAR, creating a class with the same package namespace definition, and being able to access our variable through the getter?
We thought about getting rid of all getters for the specific variable, and giving the variable value to other classes with setters and constructors, when they pass a reference to themselves. Obviously, they will be final classes. This way all objects needing the variable value have their own private copy.
I'm wondering though if there is a better way?

Access control modifiers (public, private, protected) are not meant as a security tool, but as an OO design tool. They're used to implement OO patterns like encapsulation, inheritance.
Even with no getter whatsoever and a private variable, any Java developer can use reflection to access the variable.
If you want to keep something secret, don't ever put it in a variable of a program executed by anyone. Keep it on your own machines.

- Reflection seems to be the evil here, using which any variable even with private access modifier can be accessed.
- Four access controls like private, default, protected, and public are introduced in Java more as a tool to support the Core Object Oriented Concept like Inheritance, Encapsulation etc...

Related

private access modifier and protected access modifier [duplicate]

This question already has answers here:
What is the difference between public, protected, package-private and private in Java?
(30 answers)
Closed 8 years ago.
I have a problem understanding access modifiers in Java.
public: can be used anywhere.
private: can only be used inside the same class.
protected: can only be used in subclasses.
I saw many examples and tried but I couldn't understand.
I know only the definition. Please any one help me one this give me more examples.
What kind of programs would use private?
What kind of programs would use protected?
What kind of programs would use public?
This is very basic in OOP concepts. When the class should need to not to expose it parameters, it would define them as "private". Any class outside have no any access to it. Either these variables are for the use of the class itself only or there are public getters and setters which give indirect but controlled access to these variables.
example is age. Let say someone need to set minus value to age, then the setter method can avoid setting that value. It is a bad practice in OOP to expose variables as public. If you do that, any other logic which can create an instance of the class can change the value of the varible.
The variables are marked "protected" when we need to allow sub classes too can use or have access to these variables.
Mostly public access modifier is used for methods
You would use all three in all kinds of programs, except for very simple programs where everything is typically public.
A good practice is to use the most restrictive access modifier that you can. Access modifiers exist to help you stop yourself from making mistakes - they are not actually required per se, but they are very useful. If you're writing a library for other people to use (which you aren't, but you might in the future) they also stop other people doing weird things with your code.
Usually, a class is related to one thing (e.g. a book in a library). If you are writing a library system, you might have a class like this:
public class Book
{
private String title;
public String getTitle() {return title;}
public Book(String t) {title = t;}
...
}
Notice that title is private, so you can't directly get or set the title of a Book. You can indirectly get it using the getTitle method, which is public. You can only set it once, when the Book is created.
Code inside the Book class can still set the title, so this is not foolproof. final would be better for that, but this is to demonstrate access modifiers, not final.
You could just make title public, and say that you won't change the title of a book, but later you might do it by mistake. Again, access modifiers help you prevent yourself (and sometimes other people) making mistakes.
Edit: Also, you're wrong about protected. protected things are accessible to subclasses or classes in the same package. There's also a default access modifier, which has no keyword, which you get if you don't use public, protected or private. The default access modifier makes things accessible to the same package only.
private is used when you have variables or methods in a class which you will not use outside the class.
public is used for variables and methods which need to be accessed outside this class.
protected is used when the variables need to be used only that class and in its child class.
here is a good example.

What is the purpose of access modifiers?

I know this applies to many languages, and not just Java, but that is the language I'm most familiar with.
I understand what the modifiers do, and how to use them. I just want to know, why do we need them? Why can't every object be accessible, whether or not it needs to be?
The reason becomes more apparent when you have to maintain a larger project. When a method or variable is public, you have to be careful when you make changes to it, because you never know which parts of the codebase rely on its exact behavior.
But when a variable or method is private, you know that it is not used outside of the class. That means there is a lot less code you have to pay attention to when you make changes.
By making class features private and public, you clearly separate the interface to the outside world from the internals. The less you exposes to the outside world, the more freedom you have with what the internal implementation does.
When you, for example, always make variables private and accessed them through getters and setters, you can later change them from a variable to a computed value, and then even later add caching to the computation for performance reasons. When it would be a public variable, you would have to change code everywhere the variable is used. But when you expose it to the outside world through getters and setters, all other code can keep using the class as if nothing had changed.
Making fields and methods private keeps other classes from improperly depending on the specific details of how a class works. The public interface (and the best case of all, an actual interface) describes how client code should interact with a library based on the semantics of the work being done. The implementer is then free to use whatever appropriate techniques to implement that interface and can make significant behind-the-scenes changes knowing that the client code will keep working.
An everyday example is the Collections group of interfaces. Most of the time, it's not important logically for code to know what particular kind of Set is in use, just that it's a collection that supports certain operations and doesn't have duplicates. This means that a method that accepts a Set<Integer> will work with any Set, including HashSet and ImmutableSet, because the person who wrote the interface wasn't poking around in the implementation's internals.
An example where this breaks down is the unfortunate tendency of some programmers to use packages in the com.sun namespace, especially when using cryptography. Upgrading to a new version of the JRE routinely breaks this code, which would have worked fine if the programmer had used the proper javax.crypto interfaces and factory methods instead of poking around in the JVM internals.
More or less they are used to control who can access your member variables and functions. It's the broader concept of encapsulation at work in Java(http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)).
From the Oracle Docs:
Access level modifiers determine whether other classes can use a
particular field or invoke a particular method. There are two levels
of access control:
At the top level—public, or package-private (no explicit modifier).
At the member level—public, private, protected, or package-private (no
explicit modifier).
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
As to why you should do this:
It has to do with intent of use. It would probably be best described as a design choice that helps guide usage through-out the code-base. By marking something private you are telling other developers that this field or method should not be used outside it's current purpose. It really becomes important on large projects that shuffle developers over time. It helps communicate the purpose & intended uses of classes.
To avoid other classes having direct access to internal members of the class.
This is most useful for avoiding that member variables are mutated in an uncontrolled way (e.g. without proper validation, without notifying listeners, ...).
Another reason to avoid this is that the internal implementation may change at any time but you don't want to break code that uses it.
As others have noted, the concept is called Encapsulation.
Access modifiers are there to set access levels for classes, variables, methods and constructors. This provides an individual with the chance of controlling better the privacy of the application. There are 4 access modifiers.
Modifier | Class | Package | Subclass | World
no modifier:--|----yes----|------yes--------|--------no--------|-----no----|
private:-------|----yes----|-------no--------|--------no--------|-----no----|
public:--------|----yes----|------yes--------|-------yes-------|----yes----|
protected:---|----yes----|------yes--------|-------yes-------|-----no-----|
Regarding your question, we do need and use access modifiers because we need to restrict whom can call our program and in what way.
Also, when it comes to variables if you make something public, that means that I have direct access to it. Therefore, I am allowed to do whatever I want without following your guidelines through your methods.
For example:
public int maxUsers;
public void setMaxUsers(int users) throws IllegalArgumentException{
if(users > 0 && users <= 1000){
maxUsers = users;
}else{
throw new IllegalArgumentException("The users can not be less than 0 or greater than 1000")"
}
}
Imagine your whole program being based on its maxUsers. Since, you give me the right to access that variable directly, I could do this: maxUsers = -15; and not use the setMaxUsers method, which will simply make your program behave in an abnormal way (in the best case).
Explanations
A private member is only accessible within the same class as it is declared.
A member with no access modifier is only accessible within classes in the same package.
or
If a variable is set to protected inside a Class, it will be accessible from its sub classes defined in the same classes or different package only via Inheritance.
A protected member is accessible within all classes in the same package and within subclasses in other packages.
A public member is accessible to all classes (unless it resides in a module that does not export the package it is declared in
Here's a better version of the table. (Future proof with a column for modules.)

Compiling Java files

I am building an API for my application as a middle layer between model and the controller.
The model contains all data and low-level function. I have created a new class for API which uses the model but makes things easier for the user and does not let the user to access the data directly.
Now, I would like to prevent the user from accessing the model and let him to use only the functions from API.
How do I do that?
As far as I believe, this can be simply done by specifying whether the method or variable is private or public. The problem is that I have many static fields for global data. Can I restrict access to static fields so that only private functions of API can access them?
Creating a private static field in a class will ensure that ONLY functions in that class will have access to those fields. Also, if the class is re-instantiated (aka new myClass();), those fields will not be recreated; their values will remain intact and global to all instances of myClass.
In addition to the already posted answer:
It depends on what you mean by "restrict access to static fields":
If you want to prevent others from using them directly inadvertently, use the "private" modifier.
But remember that one can still access them via reflection if no other countermeasures have bin put into place.
This holds true also for the "static int foo" case if you don't seal the package since one can easily put another class into the same package which will have access again.
If you are building an API, maybe you want to read the book Practical API Design, Confessions of a Java Framework Architect.
A Method Is Better Than a Field It's better to use methods —typically getters and setters— to access fields than to expose them directly.
A Factory Is Better Than a Constructor You facilitate an API's future evolution when you expose a factory method rather than a constructor.
Make Everything Final For the sake of future evolution, it's better to disallow subclassing ... make your class final.
...

Making an attribute of a Java object accesible by that object only

Is there a way in Java to express that an attribute x of an object o can be accessed (I mean by dot notation o.x) only by o itself? To be clear: I'm talking about object-level access as in Smalltalk, not class-level access (thus private is not private enough)?
I'm sorry - I'm sure this has been asked many times before, but I seem to pick the wrong keywords when searching.
It is not possible in Java (nothing is more private than the fields marked as "private"), but if you think about it, it is also logical: you can modify private fields of other objects only in the common class source code, and if you control the class source code, you could do any bad or good things anyway.
BTW, you can access even private variables of other classes via reflection, if there is no security manager installed, or the policy of the security manager allows it, see this: Why is it allowed to access Java private fields via reflection?
What you want to do is not possible. Every object has its own set of instance variables and can be accessed through that object only as long as they aren't static. So in short, if you want an attribute of Java object accessible by that object only, keep that object alive :).

Private and public java access modifier basics

I am relatively new to java and I did some reading about private and public acccess modifiers. I would like to eliminate any confusion once and forall in this topic because I feel like I don't have the best grasp on it.
Access modifiers in variables
Please correct me if I am wrong, a variable is public on default. If the access modifier is set to public or just not set at all, than other classes from the same project can access the integer and/or modify it. If it is private than it is not visible to the outside and cannot be accessed by classes outside the one in which it was created.
Accesss modifiers in classes
Access modifiers in classes, I don't seem to fully understand. As far as my understanding, if I call a private method from method that is not in the same class, than it will not work. If it is public than it will?
Is there anything I am missing or don't understand correctly?
I appreciate help in this regard.
Please correct me if I am wrong, a variable is public on default.
You're wrong. Assuming you mean fields, by default, they have "package" access, which can't be expressed explicitly. Local variables have no concept of access control - they only exist within the context of a method anyway, so can't be referred to from anywhere else.
If the access modifier is set to public or just not set at all, than other classes from the same project can access the integer and/or modify it.
If it's set public, then any code can access it.
If it's default (package) access, then any code in the same package can access it.
Access modifiers in classes, I don't seem to fully understand. As far as my understanding, if I call a private method from method that is not in the same class, than it will not work. If it is public than it will?
That's pretty much right, yes.
I suggest you read the Java tutorial on all of this, and consult the language spec section 6.6 for more details.
Here's a good doc on the subject.
There are four access levels:
private: Only that class (not even descendants) can access.
protected: Only that class and its descendants and classes in the same package can access.
package-private (no specifier)--only classes in the same package can access--even subclasses that are not in the same package cannot.
public: Everything can access.
For for both classes member variables and methods, the default access is package private.
You can find information about the 4 modifiers here on Oracles website.
If you do not specify the modifier, it is said to be on default, which means only any code in the same package can access it.
If it's set public, then any code in any package can access it.
Actually in Java there are four different access modifiers, private, public, protected and package specific. "Please correct me if I am wrong, a variable is public on default" - you are wrong here a variable if not declared differently has a package related access. If it is set to public then it can be modified by other classes even outside of the original package. This website - http://javapapers.com/core-java/access-modifiers-in-java-explain/ - can provide you useful hints. Actually it is very easy once you read a bit more on OO concepts such as Encapsulation. Then you will understand the purpose of access modifiers (to ensure data integerity).
Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:
Default : Visible to the package. No modifiers are needed.
Private : Visible to the class only.
Public : Visible to the world. All classes and packages.
Protected : Visible to the package and all subclasses.
If no access modifier is specified by the programmer, default access modifier is used.
Access Modifiers:
Public - {Can access anywhere in the project}
Private - {Can access only inside the class}
Protected - {Can access within the package and sub classes}
Default - {can access within the package}
Non-Access Modifiers:
Static - {for creating class variable and method}
Final - {for creating finalized class, variable and method}
Abstract - {for creating abstract method and class}
Synchronized - {for threads}
To learn more follow this link
private and public java access specifiers.in java,private access specifiers it specifies the access.private is like own family property that can uses only which family belongs.that means inside the class,method and variable can be used.
public is like government properties that means every one can access the properties without any need of tokens
private and public java access specifiers.in java,private access specifiers it specifies the access.
private is like own family property that can uses only which family
belongs.that means inside the class,method and variable can be used
.
public is like government properties that means every one can access
the properties without any need of tokens

Categories