Make java methods visible only to specific classes

I have a manager class that is responsible for managing objects of a certain type. To do this, he needs to manipulate these objects, but these objects have nothing to do with the manager, so technically design them in separate packages "project.managers" and "project.objects". The important thing is that the objects in question should be managed only by managers and nowhere else, but should be accessible to all other classes of the project.

As such, I would like managers to have access to method manipulation, but to restrict access to all other classes. The most obvious would be to move the manager class and the object class into the same package and declare protected manipulation methods, but since managers and objects are completely separate objects, they are not philosophical.

(This is partly due to the fact that I want my IDE to stop showing me manipulation methods whenever I autocomplete the code for the objects in question, so I always need to go through the dispatcher so that the corresponding tables are correctly updated every time when I change objects in question).

Are there any ideas for this, or is the obvious way the best way anyway?

+4
source share
3 answers

Why not have an interface called

ManagerFunctions 

and the other is called

 ClientFunctions 

Managed objects will implement both of these objects.

When you create managed objects, you pass them, but only as references to ClientFunctions . However, dispatcher objects refer to them as ManagerFunctions and therefore have access to their “managed” functions. Appropriate casting will simply infer the appropriate methods.

Your IDE will automatically provide you with the appropriate methods, depending on how these objects are referenced.

+4
source

You ask for something similar to C ++ 'friend' declarations, but there is no direct equivalent in Java - the visibility of the package is the closest. Alternatively, you can go for a model such as the XML DOM, where the methods that should be public are defined in the interfaces, and all client access is through these interfaces. A manager would know a specific implementation class, so he could reset it as needed.

0
source

As such, I would like managers to have access to method manipulation, but to restrict access to all other classes. The most obvious would be to move the manager class and the object class into the same package and declare protected manipulation methods ...

Technically, you are declaring a protected package of manipulation methods (without a modifier at all). Protected methods simplify the class.

but since managers and objects are completely separate objects, they are philosophically unsuitable.

I understand. Java does not have a friend declaration that C ++ has.

You can comment on manipulation methods, but this will not solve the Eclipse problem.

0
source

Source: https://habr.com/ru/post/1446960/


All Articles