| Author |
How to make private member more secure ?
|
Manoja
Greenhorn
Joined: Nov 10, 2004
Posts: 6
|
|
In below example I am able to access the private member variable in subclass.Is there any way I can protect my private member variable? Means no way it will be accessible. -------------------------- class SuperClass { private int x; } class SubClass extends SuperClass { public void method() throws Exception { SuperClass obj = new SuperClass(); Field field = obj.getClass().getDeclaredField("x"); field.setAccessible(true); field.setInt(obj, 10); System.out.println("The private member x vlaue :" + field.getInt(obj)); } }
|
 |
Jeroen Wenting
Ranch Hand
Joined: Oct 12, 2000
Posts: 5093
|
|
no. If you use reflection you can break through anything (well, almost, you won't get instances of abstract classes or interfaces I think or if you do they'll be pretty useless). One more reason to be extremely careful when using reflection.
|
42
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24045
|
|
|
A SecurityManager can be configured to disallow this. This is certainly not a beginner question, though; I'll move it to Java in General (Intermediate) for further discussion.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Nicholas Cheung
Ranch Hand
Joined: Nov 07, 2003
Posts: 4982
|
|
Are there any examples for this? Could I configure how the object be created, which variables to initialize and which does not, and how the object be destroyed? Nick
|
SCJP 1.2, OCP 9i DBA, SCWCD 1.3, SCJP 1.4 (SAI), SCJD 1.4, SCWCD 1.4 (Beta), ICED (IBM 287, IBM 484, IBM 486), SCMAD 1.0 (Beta), SCBCD 1.3, ICSD (IBM 288), ICDBA (IBM 700, IBM 701), SCDJWS, ICSD (IBM 348), OCP 10g DBA (Beta), SCJP 5.0 (Beta), SCJA 1.0 (Beta), MCP(70-270), SCBCD 5.0 (Beta), SCJP 6.0, SCEA for JEE5 (in progress)
|
 |
Petr Blahos
Ranch Hand
Joined: Apr 28, 2004
Posts: 131
|
|
Make it final. You will be able to set is accessible but not to change the value. P.
|
Get a better web browser:<br /><a href="http://www.mozilla.org/products/firefox/switch.html" target="_blank" rel="nofollow">http://www.mozilla.org/products/firefox/switch.html</a>
|
 |
Cay Horstmann
author
Ranch Hand
Joined: Nov 14, 2004
Posts: 77
|
|
Generally, you configure a security manager with a policy file. The simplest way to do that is to start your Java app with the command line Then place policy directives into the file . Once you have a security manager in place, reflection no longer lets you peek into private fields. To turn the feature back on, you add a directive such as to the policy file. As you can see, you don't get any fine-grained control. Either all reflection into non-public members is allowed, or it is all forbidden. Cheers, Cay
|
Author of <a href="http://www.amazon.com/exec/obidos/ASIN/0131482025/ref=jranch-20" target="_blank" rel="nofollow">Core Java 2, Volume I - Fundamentals (7th Edition)</a>
|
 |
 |
|
|
subject: How to make private member more secure ?
|
|
|