class MyClass { private static final String THING_ONE = "one"; private static final String THING_TWO = "two"; private static final String THING_THREE = "three"; static ArrayList<String> getThingFields() { ArrayList<String> a = new ArrayList<String>(); // For a static class, // we get the Class object by doing MyClass.class. // Instead of this.getClass(), etc. Class cls = MyClass.class; try { for (Field field : cls.getDeclaredFields()) { String nm = field.getName(); if (nm.startsWith("THING_")) { // Normally Field.get() wants an instance since // our fields are status pass in null a.add((String)field.get(null)); } } } catch(IllegalAccessException ex) { // Does not happen } return a; } }
Programming Tips - Java: Do reflect on a static Java class?
Date: 2012sep11
Language: Java
Keywords: reflection
Q. Java: Do reflect on a static Java class?
A. In this example, a static method gets all static
fields that begin with "THING_" ...