Note that there are some explanatory texts on larger screens.

plurals
  1. POAre private methods really safe?
    primarykey
    data
    text
    <p>In Java the <code>private</code> access modifier consider as safe since it is not visible outside of the class. Then outside world doesn't know about that method either. </p> <p>But I thought Java reflection can use to break this rule. Consider following case:</p> <pre class="lang-java prettyprint-override"><code>public class ProtectedPrivacy{ private String getInfo(){ return "confidential"; } } </code></pre> <p>Now from another class I am going to get Info:</p> <pre class="lang-java prettyprint-override"><code>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()); } } </code></pre> <p>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.</p> <p>But my point become invalid since below line of code.</p> <pre class="lang-java prettyprint-override"><code>Method method[] = new ProtectedPrivacy().getClass().getDeclaredMethods(); </code></pre> <p>Now this <code>method[]</code> 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?</p> <p>I am quote some point from <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html" rel="nofollow">Java Documentation</a> to clarify my question.</p> <blockquote> <p>Tips on Choosing an Access Level: </p> <p>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.</p> </blockquote>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload