Re: How to access a member constant by FQN
Sideswipe wrote:
Hmm, ok, let me try this:
Class.forName("com.whatever.mycompany.MyConstants");
// MyConstants is now loaded and the static members initialized
MY_CONST is now an Integer instance floating around in the JVM. So, I
don't NEED a new instance of it, but I want to access it by a fully
qualified name.
When I do: Class.newInstance() <-- object is returned but if I am
given the string: "com.whatever.mycompany.MyConstants.MY_CONST" I am
not being given a FQN to a class, I am being given a FQN to a static
final member of a Class.
Another way to say it, how do I make an assignment to this instance
based on the FQN as a String.
I don't think you fully appreciate the definition of static final...
A static member is a member that exists for all instances of the class
and only one ever exists. [*] A final variable is a variable that cannot
be reassigned after it has been assigned once. Therefore, a static final
variable is an non-reassignable variable that only ever exists once. It
is for that reason that static final primitives, String's, and Class's
(?) are inlined into the code. Furthermore, the Integer class is
immutable, so none of its fields can change, so a static final Integer
is truly unchangeable.
> This is all runtime/reflection -- not compile time so I have no way to
> know what will be referenced. If I knew the Outter class I could use
> reflection to get the fields and discover it by name, but I can't know
> that the String given to me represents a class and not one of it's
> members.
Object someConst = ?
1. Why do you need to use reflection?
2. From where is the String given to you?
3. Why can the String given to you represent a field?
4. Why do you need to reassign a static final variable?
If you still desperately want to do this, note that of any identifier,
the simple name of the class will either appear as the rightmost, second
from the right, are not at all (see the JLS). It should become clear how
to proceed...
[*] This definition will fail to hold under two conditions: the class
information is collected by the GC, or the class is redefined using
multiple class loaders. The former is generally not of too much concern,
and the latter is only important when one is deeply involved with guts
of the system, which I assume you are not.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth