aspose file tools*
The moose likes Java in General and the fly likes Getting value of static variable with Reflection ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Getting value of static variable with Reflection ?" Watch "Getting value of static variable with Reflection ?" New topic
Author

Getting value of static variable with Reflection ?

Vinicius Alves
Greenhorn

Joined: Dec 21, 2010
Posts: 14
Is it possible to get a value os a static final variable of a class with reflection ?
I can get the value of a instace variable normally starting from the a instance, since static fields are class variable
I wonder if it's possible.
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3646
    
  15
Yes. All the fields of a class (including static ones) are represented by an instance of the Field class.


Joanne
Vinicius Alves
Greenhorn

Joined: Dec 21, 2010
Posts: 14
Joanne Neal wrote:Yes. All the fields of a class (including static ones) are represented by an instance of the Field class.

Could you please show me a simple example ?
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3646
    
  15
Vinicius Alves wrote:Could you please show me a simple example ?

Why don't you give it a try first. Have you even looked at the javadoc for the Field class ?
Vinicius Alves
Greenhorn

Joined: Dec 21, 2010
Posts: 14
Answering my topic:

Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3646
    
  15
I assume you realise that will only work with String fields. You'll get a ClassCastException with any other type. If your method has to return a String, then you need to call toString on the Object returned from get().
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19718
    
  20

After checking if that return value is not null of course.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Getting value of static variable with Reflection ?