Java – Are private methods really safe

access-modifiersjavaprivatereflection

In Java the private access modifier consider as safe since it is not visible outside of the class. Then outside world doesn't know about that method either.

But I thought Java reflection can use to break this rule. Consider following case:

public class ProtectedPrivacy{

  private String getInfo(){
     return "confidential"; 
  }

}  

Now from another class I am going to get Info:

public class BreakPrivacy{

   public static void main(String[] args) throws Exception {
       ProtectedPrivacy protectedPrivacy = new ProtectedPrivacy();
       Method method = protectedPrivacy.getClass().getDeclaredMethod("getInfo", null);
       method.setAccessible(true);
       Object result = method.invoke(protectedPrivacy);
       System.out.println(result.toString());
   }
} 

At this moment I just thought still private method safe since to do some thing like above we must know method name. But if class which contain private method written by some one else we don't have visibility of those.

But my point become invalid since below line of code.

Method method[] = new ProtectedPrivacy().getClass().getDeclaredMethods();

Now this method[] contains all the things need to do above thing. My question is, is there a way to avoid this kind of things doing using Java reflection?

I am quote some point from Java Documentation to clarify my question.

Tips on Choosing an Access Level:

If other programmers use your class, you want to ensure that errors
from misuse cannot happen. Access levels can help you do this.Use the
most restrictive access level that makes sense for a particular
member. Use private unless you have a good reason not to.

Best Answer

It depends on what you mean by "safe". If you're running with a security manager that allows this sort of thing, then yes, you can do all kinds of nasty things with reflection. But then in that kind of environment the library can probably just be modified to make the method public anyway.

Access control is effectively "advisory" in an environment like that - you're effectively trusting the code to play nicely. If you don't trust the code you're running, you should use a more restrictive security manager.