Forums Register Login

Reflection: getting the value of public static final fields

+Pie Number of slices to send: Send
I'm trying to find a means to obtain the value of public static final fields in a class.

For example, given:



I'm determining the value of the class constant ABC.

So far, I've come up with:



However, that method requires that an instance of the declaring class be instantiated, therefore requiring that the declaring class have a no-args constructor. (This would be moot if I had an instance of the declaring class lying around, but I do not.)

Given that the field in question is public, static and final, it occurs to me that the value should be able to be determined without the need to instatiate an instance of the class, but I haven't been able to discern a means to do that.

Anyone know if this is possible without resorting to uber-hackery?

Extra credit: what if the field is declared in an interface?
+Pie Number of slices to send: Send
[Bear]: that method requires that an instance of the declaring class be instantiated

No, for a static field you're allowed to pass null for the instance.
+Pie Number of slices to send: Send
[Bear]: Extra credit: what if the field is declared in an interface?

Null works here too.
+Pie Number of slices to send: Send
J2SE API Specification
java.lang.reflect.Field.get(Object obj)

"If the underlying field is a static field, the obj argument is ignored; it may be null."
+Pie Number of slices to send: Send
Doh! I must've looked at those descriptions over a dozen times and just skipped right over that part.

Can I use the fact that I'm waiting on my new glasses (bifocals for the first time, no less!) as an excuse?
+Pie Number of slices to send: Send
I hate that I am repeating this, but null works for getting static methods too. I found that out last week, but I thought the Javadocs didn't have that visible to easily.

But it works, I used it to invoke a static method.



Of course, it needs to be in a try-catch statement.

Mark
+Pie Number of slices to send: Send
I have a FAQ item to demo some of reflection stuff.
This is the link:
http://bobcat.webappcabaret.net/javachina/faq/a_01.htm#misc_Q60
The airline is called "Virgin"? Don't you want a plane to go all the way? This tiny ad will go all the way:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 10182 times.
Similar Threads
NX:[URLyBird]How to use the specified Data File Format?
java STATIC fields.
Auto toString of Variables
where to declare those %&?!�$ variables
FBN: criteriaFind(String criteria) method; is this ok ?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 00:08:28.