• Post Reply Bookmark Topic Watch Topic
  • New Topic

Accessing fields via reflection.  RSS feed

 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I understand that there are two ways to get a java.lang.reflect.Field object:
1. getDeclaredFields() - returns Field[]
2. getField("field_name") - returns a Field for "field_name" ONLY IF field_name is
public in it's class.

What I am not getting is point number 2. Why can we only get a Field object of
a field that is public? We can anyways get an array of all declared fields, so
this has got nothing to do with security etc...

Looking forward to your response.

Regards,
Ven.
 
Ranch Hand
Posts: 679
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ven jovovich wrote:Why can we only get a Field object of
a field that is public? We can anyways get an array of all declared fields, so
this has got nothing to do with security etc...

That method will only let you access public fields, but the getDeclaredField method will let you access any field.
 
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ven jovovich wrote:We can anyways get an array of all declared fields, so this has got nothing to do with security etc...

No? Have a look at the @throws documentation for the two methods. You'll see that the security requirements are different, so I'd say it has everything to do with security.

Winston
 
Bartender
Posts: 5167
11
Java Netbeans IDE Opera
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Apart from which, getField(...) can retrieve an inherited field; getDeclaredFields() doesn't.
 
ven jovovich
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot guys
Although I read the doc, somehow I had overlooked @throws... damn...

Resolved.

Regards,
Ven.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!