Solved

Reflection violates the accessibility

Posted on 2002-03-04
10
563 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
 

Author Comment

by:rayhon88
ID: 6840131
u should use getDeclaredField instead of getField
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
count11 challenge 6 47
stringclean challenge 26 56
mapAB Challlenge 35 88
base64 decode encode 12 96
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

757 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now