Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting value of static variable with Reflection ?

 
Vinicius Alves
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. All the fields of a class (including static ones) are represented by an instance of the Field class.
 
Vinicius Alves
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Answering my topic:

 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20550
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After checking if that return value is not null of course.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic