Re: reflection-accessing dynamically variables from a class.
Gunther Hebein wrote:
Hello,
i am looking for a solution to the following problem.
I have declared a class that contains several static final int constants.
I want to read their values in relation to some String input from a
database.
There are several ways to do this.
1. Use enums. It sounds like you want essentially static constants,
which is what enums excel it. <enum name>.valueOf(string) is the way to
go here.
2. If you have something more complex than a static final constant, then
enums will probably not work well (they can still work, mind you, if you
contort them enough). At this point, a static Map<String, ?> works (fill
`?' with the appropriate type).
Both methods do assume that you can modify the definition of class B, or
at least keep a separate copy in reasonable sync. If you cannot, you
will have to resort to reflection. In general, avoid reflection if you
can avoid it at all.
3. Reflection. This is generally an overpowered tool for most tasks.
Warnings aside, this is how you you would use it:
|B.class.getField(string).getInt(null);|, wrapped in a few exception
handlers.
My personal preference is for way #1.
--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth