Is there a simple way to use a String which contains
a text description of a static String object to access its contents?
e.g. say s1 =getS1Value() could be "ClassA.x1" or "ClassA.x2","ClassB.x3"
etc where we know that x1,x2, etc are all static Sting's.
Can I use the contents of s1 to find the contents of x1,x2,x3 or whichever
s1 refers to?
TIA
Matt Humphrey - 08 Nov 2007 12:17 GMT
> Is there a simple way to use a String which contains
> a text description of a static String object to access its contents?
[quoted text clipped - 3 lines]
> Can I use the contents of s1 to find the contents of x1,x2,x3 or whichever
> s1 refers to?
If you simply wanted to have a collection of static constants identified by
name, I'd just make a static Map and populate it. However, if you really
want values that are distributed in different classes, the most direct
approach is to use reflection. First break the string into the class name
and the field name. The rest will look something like...
Class clazz = Class.forName (className);
Field field = clazz.getDeclaredField (fieldName);
String value = (String)field.get(null);
You can read the Javadocs for details.
Matt Humphrey http://www.iviz.com/
patrick - 08 Nov 2007 13:52 GMT
Matt,
Excellent. That works.
thanks.
patrick
>> Is there a simple way to use a String which contains
>> a text description of a static String object to access its contents?
[quoted text clipped - 17 lines]
>
> Matt Humphrey http://www.iviz.com/
Roedy Green - 09 Nov 2007 00:16 GMT
>Can I use the contents of s1 to find the contents of x1,x2,x3 or whichever
>s1 refers to?
see http://mindprod.com/jgloss/classforname.html
that lets you get the class given its name.
To call a method or get the value of a field you must use reflection.
see http://mindprod.com/jgloss/refection.html
Another technique is to compose some Java source code, compile it on
the fly and execute it.
see http://mindprod.com/jgloss/onthefly.html

Signature
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
Roedy Green - 09 Nov 2007 00:17 GMT
>e.g. say s1 =getS1Value() could be "ClassA.x1" or "ClassA.x2","ClassB.x3"
>etc where we know that x1,x2, etc are all static Sting's.
the practical way you handle this is with a HashMap of delegates. You
look up string to get delegate objects that implement some interface.
see http://mindprod.com/jgloss/delegate.html

Signature
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com