Search code examples
javaaccess-modifierspackage-private

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?


Solution

  • 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.