Solved

Reflection violates the accessibility

Posted on 2002-03-04
10
573 Views
Last Modified: 2013-12-29
hi, experts,

Recently, i am studying reflection in java.lang.reflect.*

i found out that Field and Method class has the method called setAccessible(boolean flag), once set it to true, you can access other classes private field or method... isn't that violates the accessibility in Java and the encapsulation concept? --provided by JDK1.3 or later version..

ray
0
Comment
Question by:rayhon88
  • 3
  • 2
  • 2
  • +2
10 Comments
 
LVL 3

Assisted Solution

by:saxaboo
saxaboo earned 25 total points
ID: 6838737
Hi,

according to Sun's javadoc :

'First, if there is a security manager, its checkPermission method is called with a ReflectPermission("suppressAccessChecks") permission.'

So when you setAccessible(true) (i.e. you want to disable access checks on the object), Java first verifies tht you have the right to do so.

To me, there is no security violation, at least that's what I understand from the doc.

Hope this helps,

-S

0
 
LVL 9

Expert Comment

by:Venci75
ID: 6838739
I created a class Test with a private field:
public class Test {
  private String test;
}

And executed this code:
try {
  Class cls = Test.class;
  java.lang.reflect.Field fld = cls.getField("test");
  fld.setAccessible(true);
} catch (Exception e) {
  e.printStackTrace();
}
The result was:
java.lang.NoSuchFieldException: test
     at java.lang.Class.getField0(Native Method)
     at java.lang.Class.getField(Class.java:796)
     at Demo.main(Demo.java:26)

As you can see - you can't get an instance of this private field, which is needed to get the change the accessibility.
Thus only the code, that can access this field can change the accesibility of the field. I don't think that this violates "the accessibility in Java and the encapsulation concept", becasue if a code fragment can access the field (method) - it could make the value (functionallity) available to the other code, that cannot access it.
0
 
LVL 7

Accepted Solution

by:
Igor Bazarny earned 25 total points
ID: 6839446
Hi,

If you would use getDeclaredField instead of getField(), your code wouldn't throw exception.

A bit of Class.getField() documentation:
The field to be reflected is determined by the algorithm that follows. Let C be the class represented by this object:

1. If C declares a _public_ field with the name specified, that is the field to be reflected.
2. If no field was found in step 1 above, this algorithm is applied recursively to each direct superinterface of C. The direct superinterfaces are searched in the order they were declared.
3. If no field was found in steps 1 and 2 above, and C has a superclass S, then this algorithm is invoked recursively upon S. If C has no superclass, then a NoSuchFieldException is thrown.

In contrast,
public Field[] getDeclaredFields()
                          throws SecurityException
Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields.

Unfortunately, there are no such details in getDeclaredField() doc, but experience shows that it returns private field when requested.

Yes, this is violation of encapsulation. On another hand, there are could be condition where such break of encapsulation is useful. In my opinion, setAccessible() method is intended for tool use. E.g. some persistance management library could use setAccessible() to acceess attributes to be stored into database.

Regards,
Igor Bazarny,
Brainbench MVP for Java 1,
www.brainbench.com
 
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:rayhon88
ID: 6840131
u should use getDeclaredField instead of getField
0
 

Author Comment

by:rayhon88
ID: 6840133
great answer bazamy..but the answer from saxaboo is helpful too..
question is how to set up the security check? give me some guideline on this saxaboo...

thanks

ray
0
 
LVL 7

Expert Comment

by:Igor Bazarny
ID: 6843658
Hi,

Check out this document:
http://java.sun.com/j2se/1.3/docs/guide/security/PolicyFiles.html

For applet related permission should not be granted, and I don't think that ensuring proper encapsulation using security permissions is worth spent efforts. As my experience shows, not many developers know about this way of member access, and those who know typically understand consequences.

BTW, in stand-alone application mentioned permission granted to everyone (hmm, I need to refresh this, it could be that in standalone mode there is no security manager at all, so all permissions are granted to everyone)

Regards,
Igor Bazarny
0
 

Author Comment

by:rayhon88
ID: 6845359
All i worry is that if hacker knows the class contract like Customer class, can he see the private information for the Customer with this mechanism? Normally, if RMI that may pass the serialized objects for remote usage, will it possibly be stolen by the hacker during the network transportation?

ray
0
 
LVL 35

Expert Comment

by:girionis
ID: 8658534
No comment has been added lately, so it's time to clean up this TA.

I will leave a recommendation in the Cleanup topic area that this question is:

- points to bazarny@idg

Please leave any comments here within the
next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !

girionis
Cleanup Volunteer
0
 
LVL 35

Expert Comment

by:girionis
ID: 8738535
 I actually recommended points only to bazarny :-)
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
servlet and mdb, jms error 1 57
glassfish admin console 1 21
junit example issue 2 25
activeMQ Queue Messages Enqueued and Messages Dequeued 1 32
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This video teaches viewers about errors in exception handling.

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question