fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.lang.reflect.Field;
  4. import java.lang.reflect.Modifier;
  5. import java.util.TreeSet;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone {
  9. public static void main (String[] args) throws java.lang.Exception {
  10. System.out.println( "Keys1: " + new Keys1().keySet() );
  11. System.out.println( "Keys2: " + new Keys2().keySet() );
  12. }
  13. }
  14.  
  15. class Keys1 {
  16. public static final ClassValue<TreeSet<String>> KEYS = new ClassValue<TreeSet<String>>() {
  17. @Override protected TreeSet<String> computeValue(Class<?> type) {
  18. final int desired=Modifier.PUBLIC|Modifier.STATIC|Modifier.FINAL;
  19. Field[] fields=type.getDeclaredFields();
  20. TreeSet<String> set = new TreeSet<>();
  21. for(Field f: fields) {
  22. if((f.getModifiers()&desired)==desired && f.getType()==String.class) try {
  23. set.add((String)f.get(null));
  24. } catch(IllegalAccessException ex) {
  25. throw new AssertionError(ex);
  26. }
  27. }
  28. for(Class<?> inner: type.getDeclaredClasses()) {
  29. set.addAll(get(inner));
  30. }
  31. type = type.getSuperclass();
  32. if(type != null && type != Object.class) set.addAll(get(type));
  33. return set;
  34. }
  35. };
  36. public TreeSet<String> keySet() {
  37. return KEYS.get(getClass());
  38. }
  39.  
  40. public static final String AFIELD = "example";
  41. }
  42.  
  43. // no additional steps required, the inherited keySet() does the job
  44. class Keys2 extends Keys1 {
  45. public static final String ANOTHER_FIELD = "subclass example";
  46.  
  47. static class Inner {
  48. public static final String FIELD = "innerclass example";
  49. }
  50. }
Success #stdin #stdout 0.05s 4386816KB
stdin
Standard input is empty
stdout
Keys1: [example]
Keys2: [example, innerclass example, subclass example]