0

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!

Anshul Sharma
  • 1,018
  • 3
  • 17
  • 39
white-imp
  • 313
  • 2
  • 16

2 Answers2

1

You should use:

    for (Class<?> item : CLASSES) {
        Field f = item.getDeclaredField("PROPERTY");
        string.equals(f.get(item));
    }
Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66
  • The argument to `get` is ignored when the field is static. – matt Aug 10 '20 at 09:34
  • Thanks, but using 'getField' or 'getDeclaredField' gives me "Unhandled exception: java.lang.NoSuchFieldException". What It could be? – white-imp Aug 10 '20 at 09:39
  • Can you share more of your code? it shouldn't be. Make sure you provide correct field name. – Giorgi Tsiklauri Aug 10 '20 at 09:51
  • @matt true, but you still need to provide an argument if using `get()`. – Giorgi Tsiklauri Aug 10 '20 at 10:38
  • I think semantically it is better to use `null` because the argument should be an instance of the class. The argument you're passing is an instance of a different object: `Class`. It's ignored anyways, so it's a moot point. – matt Aug 10 '20 at 11:03
1

Did you mean how to deal with the exception?

enter code here
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
    Class<?>[] classes = new Class[] { ClassA.class, ClassB.class, };

    for (Class<?> item : classes) {
        Field f = item.getDeclaredField("PROPERTY");
        System.out.println(f.get(item));
    }
}
enter code here
public static void main(String[] args) {
    Class<?>[] classes = new Class[] { ClassA.class, ClassB.class, };

    for (Class<?> item : classes) {
        try {
            Field f = item.getDeclaredField("PROPERTY");
            System.out.println(f.get(item));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
polaris
  • 11
  • 1