Solved

Reflection violates the accessibility

Posted on 2002-03-04
10
567 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
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 

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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

Suggested Solutions

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

786 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