0

I want to get a list of fields that have a common super class from an object and then iterate on them and perform a method existing in the super class. Example :

class BasePage{
***public void check(){}***
}

class Page extends BasePage{
    private TextElement c;
    private ButtonElement e;

    //methods acting on c and e
}

class TextElement extends BaseElement {

}

class ButtonElement extends BaseElement {

}

class BaseElement {
    public void exits(){};
}

So from the BasePage class I want to implement the check method which should parse the list of fields of a page, then get the list of the fields having the super class baseElement, then for each one launch the method exists. I confirm it is not a duplicate of the reflection private fields

Medj
  • 15
  • 5
  • You can achieve this using [reflection](https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getDeclaredFields()), and changing your class structure to call a virtual method in your abstraction. – nortontgueno Mar 07 '19 at 15:55
  • Possible duplicate of [Java reflection get all private fields](https://stackoverflow.com/questions/15315368/java-reflection-get-all-private-fields) – Markus Mitterauer Mar 07 '19 at 16:04

1 Answers1

2

The following code should do what you are expecting. I have marked what the code does and how it works in the comments.

public static void main(String[] args) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    Page page = new Page();
    Collection<Field> fields = getFieldsWithSuperclass(page.getClass(), BaseElement.class);
    for(Field field : fields) { //iterate over all fields found
        field.setAccessible(true);
        BaseElement fieldInstance = (BaseElement) field.get(pageCreated); //get the instance corresponding to the field from the given class instance
        fieldInstance.exists(); //call the method
    }
}

private static Collection<Field> getFieldsWithSuperclass(Class instance, Class<?> superclass) {
    Field[] fields = instance.getDeclaredFields(); //gets all fields from the class

    ArrayList<Field> fieldsWithSuperClass = new ArrayList<>(); //initialize empty list of fields
    for(Field field : fields) { //iterate over fields in the given instance
        Class fieldClass = field.getType(); //get the type (class) of the field
        if(superclass.isAssignableFrom(fieldClass)) { //check if the given class is a super class of this field
            fieldsWithSuperClass.add(field); //if so, add it to the list
        }
    }
    return fieldsWithSuperClass; //return all fields which have the fitting superclass
}
Ian Rehwinkel
  • 2,486
  • 5
  • 22
  • 56
  • The first part is great! But it is throwing a java.lang.IllegalAccessException on this line : Object fieldInstance = field.get(pageCreated); – Medj Mar 07 '19 at 16:31
  • I added an update to fix the IllegalAccessException. Thanks Ian Rehwinkel – Medj Mar 07 '19 at 16:50