Getters/(Setters) for classes? - java

A friend of mine just brought up that I should use getters for classes, is this considered good practice or not? I couldn't find the answer elsewhere.
And how about Setters for classes? Does that even exist?
Thanks for your input.
public class Movement {
private Player p;
public Movement(Player p) {
this.player = p;
}
// methods
}
public class Player {
/**
* The movement class that handles all players movements
*/
private Movement movement;
public Player() {
this.movement = new Movement(this);
}
public Movement getMovement() {
return this.movement;
}
}
#people saying duplicate question
This is not simple variables that require protection by being private.
This is about the habit of adding a getter for a class, which I don't get since the class is already public.

And how about Setters for classes? Does that even exist?
AFAIK, not in Java. Whenever you want to modify class properties or behaviour, you change its members or methods respectively (by "setter" methods in some cases, yes), or you provide another constructor to a class to create some specified instance of it.
The point of getters and setters is to provide encapsulation concept, which is used, mainly, to restrict or configure access to some of the certain object's components (not the whole class instance itself).
As for classes, in Java we have access modifiers for the same reason.
My guess is that your friend may talk about something like Singleton pattern in which you're actually using some kind of "getter" method to get access to class instance like in here:
public class Singleton {
private static Singleton singleton = new Singleton( );
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton(){ }
/* Static 'instance' method */
public static Singleton getInstance( ) { //That's what you are probably asking about
return singleton;
}
/* Other methods protected by singleton-ness */
protected static void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}
Or it's about static factory pattern given as example in this answer.
Summary: Despite the fact that the class itself is public, there's no public constructors availiable, so this is the reason to provide some kind of a "getter". So this is your case, I suppose.

Getter and setter are used to hide/protect private/protected variable from
other Classes. Exemple:
Class Person{
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}

I don't see any difference between setting a member variable versus setting a object. You can set the value for an object in same was as you set the member variables.
public void setPlayer(Player player){
this.player = player;
}
public Player getPlayer(){
return player;
}
public void setMovement(Movement movement){
this.movement = movement;
}
public Movement getMovement(){
return movement;
}
If you don't want to set the object value explicitly, you can set the value in constructor and provide only getter method to callers so that no one else can set the value except by calling constructor. Even if you do not want to call constructor for setting the value, create Singleton class by making constructor as private. I hope you know how to create Singleton classes

Related

private member cannot accessible in child class but my below code give successful run why [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
` private member cannot accessible in child class but my below code give successful run but i know that the private member only accessible in that class where its define. parentclass(parent class) and childClass(child class) are two.
public class ParentClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
childClass c=new childClass();
c.display("Hazrat Ali");
System.out.println("My father name is:"+c.getName());
}
}
class childClass extends ParentClass
{
private String Name;
public void display(String n)
{
Name=n;
}
public String getName()
{
return Name;
}
}**
In your code you are setting name as private String :
private String Name;
and accessing it using a public function getName() and returning its value to the caller:
public String getName()
{
return Name;
}
and as your (getter) function getName() has a public access modifier you can
call it using child class object:
childClass c=new childClass();
c.display("Hazrat Ali");
System.out.println("My father name is:"+c.getName());
Encapsulation / Data hiding
To achieve encapsulation in Java −
Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the variables
values.
Benefits of Encapsulation
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields.
Encapsulation provide control over the data.
private members cannot be accessible directly from outside the class but can be accessed using getters and setters and here you are doing the same. You are using getter to access the Name variable so nothing is wrong in this.
making class attributes hidden from other class is called Encapsulation
To achieve encapsulation in Java −
Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the variables
values.
what you done is field name is accessible in class only as you accessed variable by getter function i assumed that you learned but using java built-in class
for working with private data you should have getter and setter function
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
You're not accessing a private variable of childClass from parentClass - you're calling public methods that access private variables of childClass. There's absolutely nothing wrong with a public method using one of its class's private variables.
Also, your main method is static, so it isn't associated with any particular instance of ParentClass. You could've just easily put this method in childClass (or some other class - it makes no difference whatever). That being said, it's not strictly accurate to say that you're actually accessing it from ParentClass - that class really doesn't have anything to do with anything here.

Private Variables inside inside a Constructor in Java

I'm confused as to why I can't denote a variable private when creating it inside a constructor or inside the main but can do it outside those inside the class.
public class Stuff
{
private double x;
public Stuff(int i, double d) {
private double y;
}
public static void main(String[] args) {
private double z;
}
}
Access modifiers don't make sense inside functions, because the variables go out of scope immediately after the function ends
A class has fields and methods that can be accessed by certain other classes, and always the class itself, depending on the access level modifiers (private, default-access, protected, or public). You can view the fields and methods as the attributes/properties of the class.
A field is what you describe as "a variable in a class that is not inside any method". A field describes a value the class has, and a method describes what the class (or the objects of the class) can do.
Ignoring the static keyword for the simplicity of this post, a class is a template for creating objects. Every object you create of a certain class will have a set of its own fields and methods (unless the field or method is static).
If you set the field of a class to private nothing outside the class can reach it. Only the class itself (essentially meaning the methods of the class) can reach it. Same goes with private methods. Only other methods of the class can reach the private methods.
Consider this example:
public class Person {
private String name;
public int id;
public Person(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
}
If somebody wanted to acess the name of this person by directly referring to the name, they would not be able to do it, since the name is private. They would have to use the method getName() to do it.
Person person = new Person(John, 5);
System.out.print(person.name); //does not work
Person person = new Person(John, 5);
System.out.print(person.getName()); //works
This is good because if the name was directly accessible, you could write:
person.name = "Felicity";
and change the name of the person, which is not wanted (we can do this with the id, and this could cause troubles). This is not possible when the name is private.
A variable inside a method, however, is not a field. Meaning it is not an attribute of the object. It is simply a temporary variable that exists to allow the method to do what it wants to do. When the method has finished executing, the variable is destroyed. Declaring such a variable as private or anything else is completely meaningless and is therefore not allowed.

Is there a way to access the variables of the calling class in a method?

At present I have a class that is calling the static method of a different class. What I am trying to do however is have the static method change a variable of the calling class, is that possible?
Example code:
public class exClass {
private int aVariable;
public exClass() {
othClass.aMethod();
}
}
public class othClass {
static void aMethod() {
// stuff happens, preferably stuff that
// allows me to change exClass.aVariable
}
}​
So what I would like to know is, if there is a way to access aVariable of the instance of exClass that is calling othClass. Other than using a return statement, obviously.
Not if aClass doesn't expose that variable. This is what encapsulation and information hiding are about: if the designer of the class makes a variable private, then only the component that owns it can modify or access it.
Of course, the dirty little secret in Java is that reflection can get you around any private restriction.
But you should not resort to that. You should design your classes appropriately and respect the designs of others.
You can pass this as a parameter to the second function.
public class exClass {
public int aVariable;
public exClass()
{
othClass.aMethod(this);
}
}
public class othClass{
static void aMethod(exClass x)
{
x.aVariable = 0; //or call a setter if you want to keep the member private
}
}
you should gave the static method in othClass the instance of exClass like othClass.aMethod(this), then you can change the variable of that instance, or make the variable static if you dont need an instance

Singleton java pattern

I can still instantiate by using constructor although in class definition it has been declared as private constructor??? Here is code snippet:
public class Singleton {
private static Singleton instance;
private String name;
/* Private constructor prevents other classes from instantiating */
private Singleton(String name) {
this.name = name;
// Optional code
}
/*
* Static factory method that creates instance instead of constructor.
* Synchronization helps to block any attempt to instantiate from simultaneous
* thread hence break concept of singleton.
* This method uses a technique known as lazy instantiation.
*/
public static synchronized Singleton getInstance(String name) {
if (instance == null) {
instance = new Singleton(name);
}
return instance;
}
/* Override Object clone method to avoid cloning */
#Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
public String getName() {
return name;
}
/* Example of using singleton object */
public static void main(String[] args) {
Singleton a = new Singleton("Hoang");
Singleton b = new Singleton("Shiha");
System.out.println(a.getName());
System.out.println(b.getName());
}
You can still instantiate it because your test main() method, being in the same class, has access to the private constructor: private means "only available to this class".
Put your test in another class, and you'll get what you expect.
Your test method is within the same class -> it has access to private members & methods.
Refer to this question for more info on the Singleton pattern in Java :)
You are able to instantiate the singleton because you are doing it from a method inside the Singleton's class definition (hint, you can access private methods within the class that define them.
Try doing that from outside your Singleton, and it will fail. On another note, Singleton are typically defined as final (very rare that you legitimately need to extend a Singleton class).
On another note, one typically puts some sort of guard condition (.ie. throwing a UnsupportedOperationException) on the default (and private) constructor to defend against accidental (or malicious attack) access to it via reflection.
/* default constructor made private and defended against reflection access */
private Singleton() {
throw new UnsupportedOperationException("naughty boy");
}
To be sure to instanciate it just once, you may use the Singleton Enum pattern:
public enum MySingleton {
INSTANCE("My singleton name");
private MySingleton(String name) {
this.name = name;
}
private String name;
public String getName() {
return this.name;
}
}
An enum is in some way a list of singletons sharing the same interface

Is there a way to simulate the C++ 'friend' concept in Java?

I would like to be able to write a Java class in one package which can access non-public methods of a class in another package without having to make it a subclass of the other class. Is this possible?
Here is a small trick that I use in JAVA to replicate C++ friend mechanism.
Lets say I have a class Romeo and another class Juliet. They are in different packages (family) for hatred reasons.
Romeo wants to cuddle Juliet and Juliet wants to only let Romeo cuddle her.
In C++, Juliet would declare Romeo as a (lover) friend but there are no such things in java.
Here are the classes and the trick :
Ladies first :
package capulet;
import montague.Romeo;
public class Juliet {
public static void cuddle(Romeo.Love love) {
Objects.requireNonNull(love);
System.out.println("O Romeo, Romeo, wherefore art thou Romeo?");
}
}
So the method Juliet.cuddle is public but you need a Romeo.Love to call it. It uses this Romeo.Love as a "signature security" to ensure that only Romeo can call this method and checks that the love is real so that the runtime will throw a NullPointerException if it is null.
Now boys :
package montague;
import capulet.Juliet;
public class Romeo {
public static final class Love { private Love() {} }
private static final Love love = new Love();
public static void cuddleJuliet() {
Juliet.cuddle(love);
}
}
The class Romeo.Love is public, but its constructor is private. Therefore anyone can see it, but only Romeo can construct it. I use a static reference so the Romeo.Love that is never used is only constructed once and does not impact optimization.
Therefore, Romeo can cuddle Juliet and only he can because only he can construct and access a Romeo.Love instance, which is required by Juliet to cuddle her (or else she'll slap you with a NullPointerException).
The designers of Java explicitly rejected the idea of friend as it works in C++. You put your "friends" in the same package. Private, protected, and packaged security is enforced as part of the language design.
James Gosling wanted Java to be C++ without the mistakes. I believe he felt that friend was a mistake because it violates OOP principles. Packages provide a reasonable way to organize components without being too purist about OOP.
NR pointed out that you could cheat using reflection, but even that only works if you aren't using the SecurityManager. If you turn on Java standard security, you won't be able to cheat with reflection unless you write security policy to specifically allow it.
The 'friend' concept is useful in Java, for example, to separate an API from its implementation. It is common for implementation classes to need access to API class internals but these should not be exposed to API clients. This can be achieved using the 'Friend Accessor' pattern as detailed below:
The class exposed through the API:
package api;
public final class Exposed {
static {
// Declare classes in the implementation package as 'friends'
Accessor.setInstance(new AccessorImpl());
}
// Only accessible by 'friend' classes.
Exposed() {
}
// Only accessible by 'friend' classes.
void sayHello() {
System.out.println("Hello");
}
static final class AccessorImpl extends Accessor {
protected Exposed createExposed() {
return new Exposed();
}
protected void sayHello(Exposed exposed) {
exposed.sayHello();
}
}
}
The class providing the 'friend' functionality:
package impl;
public abstract class Accessor {
private static Accessor instance;
static Accessor getInstance() {
Accessor a = instance;
if (a != null) {
return a;
}
return createInstance();
}
private static Accessor createInstance() {
try {
Class.forName(Exposed.class.getName(), true,
Exposed.class.getClassLoader());
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
}
return instance;
}
public static void setInstance(Accessor accessor) {
if (instance != null) {
throw new IllegalStateException(
"Accessor instance already set");
}
instance = accessor;
}
protected abstract Exposed createExposed();
protected abstract void sayHello(Exposed exposed);
}
Example access from a class in the 'friend' implementation package:
package impl;
public final class FriendlyAccessExample {
public static void main(String[] args) {
Accessor accessor = Accessor.getInstance();
Exposed exposed = accessor.createExposed();
accessor.sayHello(exposed);
}
}
There are two solutions to your question that don't involve keeping all classes in the same package.
The first is to use the Friend Accessor/Friend Package pattern described in (Practical API Design, Tulach 2008).
The second is to use OSGi. There is an article here explaining how OSGi accomplishes this.
Related Questions: 1, 2, and 3.
As far as I know, it is not possible.
Maybe, You could give us some more details about Your design. Questions like these are likely the result of design flaws.
Just consider
Why are those classes in different packages, if they are so closely related?
Has A to access private members of B or should the operation be moved to class B and triggered by A?
Is this really calling or is event-handling better?
eirikma's answer is easy and excellent. I might add one more thing: instead of having a publicly accessible method, getFriend() to get a friend which cannot be used, you could go one step further and disallow getting the friend without a token: getFriend(Service.FriendToken). This FriendToken would be an inner public class with a private constructor, so that only Service could instantiate one.
Here's a clear use-case example with a reusable Friend class. The benefit of this mechanism is simplicity of use. Maybe good for giving unit test classes more access than the rest of the application.
To begin, here is an example of how to use the Friend class.
public class Owner {
private final String member = "value";
public String getMember(final Friend friend) {
// Make sure only a friend is accepted.
friend.is(Other.class);
return member;
}
}
Then in another package you can do this:
public class Other {
private final Friend friend = new Friend(this);
public void test() {
String s = new Owner().getMember(friend);
System.out.println(s);
}
}
The Friend class is as follows.
public final class Friend {
private final Class as;
public Friend(final Object is) {
as = is.getClass();
}
public void is(final Class c) {
if (c == as)
return;
throw new ClassCastException(String.format("%s is not an expected friend.", as.getName()));
}
public void is(final Class... classes) {
for (final Class c : classes)
if (c == as)
return;
is((Class)null);
}
}
However, the problem is that it can be abused like so:
public class Abuser {
public void doBadThings() {
Friend badFriend = new Friend(new Other());
String s = new Owner().getMember(badFriend);
System.out.println(s);
}
}
Now, it may be true that the Other class doesn't have any public constructors, therefore making the above Abuser code impossible. However, if your class does have a public constructor then it is probably advisable to duplicate the Friend class as an inner class. Take this Other2 class as an example:
public class Other2 {
private final Friend friend = new Friend();
public final class Friend {
private Friend() {}
public void check() {}
}
public void test() {
String s = new Owner2().getMember(friend);
System.out.println(s);
}
}
And then the Owner2 class would be like this:
public class Owner2 {
private final String member = "value";
public String getMember(final Other2.Friend friend) {
friend.check();
return member;
}
}
Notice that the Other2.Friend class has a private constructor, thus making this a much more secure way of doing it.
The provided solution was perhaps not the simplest. Another approach is based on the same idea as in C++: private members are not accessible outside the package/private scope, except for a specific class that the owner makes a friend of itself.
The class that needs friend access to a member should create a inner public abstract "friend class" that the class owning the hidden properties can export access to, by returning a subclass that implement the access-implementing methods. The "API" method of the friend class can be private so it is not accessible outside the class that needs friend access. Its only statement is a call to an abstract protected member that the exporting class implements.
Here's the code:
First the test that verifies that this actually works:
package application;
import application.entity.Entity;
import application.service.Service;
import junit.framework.TestCase;
public class EntityFriendTest extends TestCase {
public void testFriendsAreOkay() {
Entity entity = new Entity();
Service service = new Service();
assertNull("entity should not be processed yet", entity.getPublicData());
service.processEntity(entity);
assertNotNull("entity should be processed now", entity.getPublicData());
}
}
Then the Service that needs friend access to a package private member of Entity:
package application.service;
import application.entity.Entity;
public class Service {
public void processEntity(Entity entity) {
String value = entity.getFriend().getEntityPackagePrivateData();
entity.setPublicData(value);
}
/**
* Class that Entity explicitly can expose private aspects to subclasses of.
* Public, so the class itself is visible in Entity's package.
*/
public static abstract class EntityFriend {
/**
* Access method: private not visible (a.k.a 'friendly') outside enclosing class.
*/
private String getEntityPackagePrivateData() {
return getEntityPackagePrivateDataImpl();
}
/** contribute access to private member by implementing this */
protected abstract String getEntityPackagePrivateDataImpl();
}
}
Finally: the Entity class that provides friendly access to a package private member only to the class application.service.Service.
package application.entity;
import application.service.Service;
public class Entity {
private String publicData;
private String packagePrivateData = "secret";
public String getPublicData() {
return publicData;
}
public void setPublicData(String publicData) {
this.publicData = publicData;
}
String getPackagePrivateData() {
return packagePrivateData;
}
/** provide access to proteced method for Service'e helper class */
public Service.EntityFriend getFriend() {
return new Service.EntityFriend() {
protected String getEntityPackagePrivateDataImpl() {
return getPackagePrivateData();
}
};
}
}
Okay, I must admit it is a bit longer than "friend service::Service;" but it might be possible to shorten it while retaining compile-time checking by using annotations.
In Java it is possible to have a "package-related friendness".
This can be userful for unit testing.
If you do not specify private/public/protected in front of a method, it will be "friend in the package".
A class in the same package will be able to access it, but it will be private outside the class.
This rule is not always known, and it is a good approximation of a C++ "friend" keyword.
I find it a good replacement.
I think that friend classes in C++ are like inner-class concept in Java. Using inner-classes
you can actually define an enclosing class and an enclosed one. Enclosed class has full access to the public and private members of it's enclosing class.
see the following link:
http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Not using a keyword or so.
You could "cheat" using reflection etc., but I wouldn't recommend "cheating".
I think, the approach of using the friend accessor pattern is way too complicated. I had to face the same problem and I solved using the good, old copy constructor, known from C++, in Java:
public class ProtectedContainer {
protected String iwantAccess;
protected ProtectedContainer() {
super();
iwantAccess = "Default string";
}
protected ProtectedContainer(ProtectedContainer other) {
super();
this.iwantAccess = other.iwantAccess;
}
public int calcSquare(int x) {
iwantAccess = "calculated square";
return x * x;
}
}
In your application you could write the following code:
public class MyApp {
private static class ProtectedAccessor extends ProtectedContainer {
protected ProtectedAccessor() {
super();
}
protected PrivateAccessor(ProtectedContainer prot) {
super(prot);
}
public String exposeProtected() {
return iwantAccess;
}
}
}
The advantage of this method is that only your application has access to the protected data. It's not exactly a substitution of the friend keyword. But I think it's quite suitable when you write custom libraries and you need to access protected data.
Whenever you have to deal with instances of ProtectedContainer you can wrap your ProtectedAccessor around it and you gain access.
It also works with protected methods. You define them protected in your API. Later in your application you write a private wrapper class and expose the protected method as public. That's it.
If you want to access protected methods you could create a subclass of the class you want to use that exposes the methods you want to use as public (or internal to the namespace to be safer), and have an instance of that class in your class (use it as a proxy).
As far as private methods are concerned (I think) you are out of luck.
I agree that in most cases the friend keyword is unnecessary.
Package-private (aka. default) is sufficient in most cases where you have a group of heavily intertwined classes
For debug classes that want access to internals, I usually make the method private and access it via reflection. Speed usually isn't important here
Sometimes, you implement a method that is a "hack" or otherwise which is subject to change. I make it public, but use #Deprecated to indicate that you shouldn't rely on this method existing.
And finally, if it really is necessary, there is the friend accessor pattern mentioned in the other answers.
A method I've found for solving this problem is to create an accessor object, like so:
class Foo {
private String locked;
/* Anyone can get locked. */
public String getLocked() { return locked; }
/* This is the accessor. Anyone with a reference to this has special access. */
public class FooAccessor {
private FooAccessor (){};
public void setLocked(String locked) { Foo.this.locked = locked; }
}
private FooAccessor accessor;
/** You get an accessor by calling this method. This method can only
* be called once, so calling is like claiming ownership of the accessor. */
public FooAccessor getAccessor() {
if (accessor != null)
throw new IllegalStateException("Cannot return accessor more than once!");
return accessor = new FooAccessor();
}
}
The first code to call getAccessor() "claims ownership" of the accessor. Usually, this is code that creates the object.
Foo bar = new Foo(); //This object is safe to share.
FooAccessor barAccessor = bar.getAccessor(); //This one is not.
This also has an advantage over C++'s friend mechanism, because it allows you to limit access on a per-instance level, as opposed to a per-class level. By controlling the accessor reference, you control access to the object. You can also create multiple accessors, and give different access to each, which allows fine-grained control over what code can access what:
class Foo {
private String secret;
private String locked;
/* Anyone can get locked. */
public String getLocked() { return locked; }
/* Normal accessor. Can write to locked, but not read secret. */
public class FooAccessor {
private FooAccessor (){};
public void setLocked(String locked) { Foo.this.locked = locked; }
}
private FooAccessor accessor;
public FooAccessor getAccessor() {
if (accessor != null)
throw new IllegalStateException("Cannot return accessor more than once!");
return accessor = new FooAccessor();
}
/* Super accessor. Allows access to secret. */
public class FooSuperAccessor {
private FooSuperAccessor (){};
public String getSecret() { return Foo.this.secret; }
}
private FooSuperAccessor superAccessor;
public FooSuperAccessor getAccessor() {
if (superAccessor != null)
throw new IllegalStateException("Cannot return accessor more than once!");
return superAccessor = new FooSuperAccessor();
}
}
Finally, if you'd like things to be a bit more organized, you can create a reference object, which holds everything together. This allows you to claim all accessors with one method call, as well as keep them together with their linked instance. Once you have the reference, you can pass the accessors out to the code that needs it:
class Foo {
private String secret;
private String locked;
public String getLocked() { return locked; }
public class FooAccessor {
private FooAccessor (){};
public void setLocked(String locked) { Foo.this.locked = locked; }
}
public class FooSuperAccessor {
private FooSuperAccessor (){};
public String getSecret() { return Foo.this.secret; }
}
public class FooReference {
public final Foo foo;
public final FooAccessor accessor;
public final FooSuperAccessor superAccessor;
private FooReference() {
this.foo = Foo.this;
this.accessor = new FooAccessor();
this.superAccessor = new FooSuperAccessor();
}
}
private FooReference reference;
/* Beware, anyone with this object has *all* the accessors! */
public FooReference getReference() {
if (reference != null)
throw new IllegalStateException("Cannot return reference more than once!");
return reference = new FooReference();
}
}
After much head-banging (not the good kind), this was my final solution, and I very much like it. It is flexible, simple to use, and allows very good control over class access. (The with reference only access is very useful.) If you use protected instead of private for the accessors/references, sub-classes of Foo can even return extended references from getReference. It also doesn't require any reflection, so it can be used in any environment.
I prefer delegation or composition or factory class (depending upon the issue that results in this problem) to avoid making it a public class.
If it is a "interface/implementation classes in different packages" problem, then I would use a public factory class that would in the same package as the impl package and prevent the exposure of the impl class.
If it is a "I hate to make this class/method public just to provide this functionality for some other class in a different package" problem, then I would use a public delegate class in the same package and expose only that part of the functionality needed by the "outsider" class.
Some of these decisions are driven by the target server classloading architecture (OSGi bundle, WAR/EAR, etc.), deployment and package naming conventions. For example, the above proposed solution, 'Friend Accessor' pattern is clever for normal java applications. I wonder if it gets tricky to implement it in OSGi due to the difference in classloading style.
I once saw a reflection based solution that did "friend checking" at runtime using reflection and checking the call stack to see if the class calling the method was permitted to do so. Being a runtime check, it has the obvious drawback.
As of Java 9, modules can be used to make this a non-issue in many cases.

Categories