mercredi 30 septembre 2015

Java reflections to get fields that are constants in interface class

I have a Java class "MyClass" which implements an interface "MyInterface". The "MyInterface" class has only constant fields(~200 fields in it).

public interface MyInterface {
public final static int NUM = 1111;
public final static String mystring = "1.1.0";
public final static int my_set1_1 = (0x0100000|4);
public final static int my_set1_2 = (0x0100000|6);
public final static int my_set2_1 = (0x001000|4);
public final static int my_set2_2 = (0x001000|6);
.
.
.
}

public MyClass implement MyInterface {
}

I am now trying to use reflection to get the constants that are declared in "MyInterface" class.

However I am unable to get the fields from the interface, irrespective of if I use getFields() or getDeclaredFields().

I tried using MyClass.getDeclaredFields() and also tried to use MyInterface.getDeclaredFields(). However I am unable to get the constants in Interface class.

Is there a way to get this?? Any ideas? Following is the code snippet of how I am trying to achieve this-

for (Class<?> currentClass = this.getClass(); currentClass != null; currentClass = currentClass.getSuperclass()) {
            Class<?>[] InterfaceClass = currentClass.getInterfaces();
            if (Arrays.asList(InterfaceClass).contains(MyInterface.class)) {
            for (Field field : currentClass.getDeclaredFields()) {
                if(field.getType() == int.class) {
                    //Do nothing
                }
            }
        }

    }





Aucun commentaire:

Enregistrer un commentaire