Search code examples
javastaticfinal

How to get static final property from ClassName.class?


I have array of classes like this.

private static final Class<?>[] CLASSES = new Class[]{
    First.class,
    Second.class,
};

Each class have property

    public static final String PROPERTY = "property_name";

Need to make loop to compare PROPERTY with specific string like this:

for (Class<?> item : CLASSES) {
    string.equals(item.PROPERTY)
}

But I could't find a way to escape from ".class" to get item.PROPERTY.

How to get PEOPERY in a correct way in this case?

Thanks!


Solution

  • You should use:

        for (Class<?> item : CLASSES) {
            Field f = item.getDeclaredField("PROPERTY");
            string.equals(f.get(item));
        }