Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outside classes accessing package-private methods

Suppose I have a class in my package org.jake and it has a method with default access (no modifier). Then the method is visible inside the package only.

However, when someone receives the jar of my framework, what is to stop them from writing a new class, declaring its package as org.jake, and using my supposedly invisible method?

In other words, is there anything I can do to prevent this?

like image 882
Jake Avatar asked May 21 '10 06:05

Jake


People also ask

Can we access private class outside the package?

Private: The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class.

Can private methods be accessed by other classes?

Just like private fields, private methods are marked with a leading # and cannot be accessed from outside their class.

Is private method accessible from inside all classes in the same package?

The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.


1 Answers

You could seal the package in your jar file. It's not bullet-proof though.

The main thing is not to rely on access modifiers etc from a security point of view to start with, really. If someone is running the code with unrestricted permissions, they're going to have access to all kinds of things. Access modifiers really just help to stop people from accidentally shooting themselves in the foot.

If someone is willing to put classes in your package to circumvent your encapsulation, they're clearly ignoring your best intentions - I say let 'em get on with it, but don't provide support for that scenario.

like image 115
Jon Skeet Avatar answered Nov 03 '22 01:11

Jon Skeet