Solved

Reflection violates the accessibility

Posted on 2002-03-04
10
578 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Technology Partners: 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

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

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

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…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses

622 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