Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Getting value of static variable with Reflection ?

 
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.
 
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
  • Likes 1
  • 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().
 
Sheriff
Posts: 21972
106
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After checking if that return value is not null of course.
 
What are you saying? I thought you said that Santa gave you that. And this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic