Perhaps the hidden question is which structure to use for keys that have a sort of hierarchy (therefore my attempt in using classes and inner classes, so that a test on specific subsets is possible). I'm looking for a structure where I can add a new key to the appropriate place and having automaticallly this key in the appropriate keySet. Here my actual try: Now I work with keys as static final String and a corresponding keySet. I often need to test if a certain key is contained in the set of keys (public static final String) declared in some other class. Therefore I extend all classes with keys from a class Keys1 which has a method keySet() that gives the set of keys. That works fine.
public class Keys1
{
private TreeSet<String> m_keySet = new TreeSet<String>();
public Keys1()
{
initKeySet();
}
private void initKeySet()
{
Field[] felder = this.getClass().getFields();
for (Field f : felder)
{
if (Modifier.isFinal(f.getModifiers()))
{
try
{
if (f.get(f) instanceof String)
{
m_keySet.add(f.get(f).toString());
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
public TreeSet<String> keySet()
{
return m_keySet;
}
}
Now I try in vain to code a similar functionality in a class Keys2 where the keySet should also contain keys that are declared in inner classes of type Keys2.
public class Keys2 extends Keys1
{
@Override
protected void initKeySet()
{
super.initKeySet();
Class<?>[] innerClasses = this.getClass().getDeclaredClasses();
for (Class<?> innerClass : innerClasses )
{
if (innerClass.getClass().isInstance(Keys1.class))
{
Keys1 newKeys;
try
{
newKeys = (Keys1) innerClass.newInstance(); // Doesn't work
keySet().addAll(newKeys.keySet());
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
}
}
}