Programming Tips - Java: Do reflect on a static Java class

Date: 2012sep11 Update: 2025oct8 Language: Java Keywords: reflection Q. Java: Do reflect on a static Java class A. In this full example, a static method gets all static fields that begin with "THING_" ...
import java.util.ArrayList; import java.lang.reflect.Field; 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. final 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; } public static final void main(String[] args) { var fields = getThingFields(); System.out.println("fields=" + fields); } }
Output:
fields=[one, two, three]