Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Reflection violates the accessibility

Posted on 2002-03-04
10
Medium Priority
?
580 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 100 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 100 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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

916 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