mercredi 2 septembre 2020

Checking For Existence of Getters in Java Without Triggering Exception

Trying to use reflection to see if a class has a getter defined for each of its fields:

Arrays.stream(entityClass.getDeclaredFields()).forEach(field -> {
    try {           
        PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(entityClass, field.getName());

        if(null == PropertyUtils.getReadMethod(pd)) {
            // no getter found, this is what I need to act on
        }
    } catch(Exception e) {
        // 
    }
});

Problem is, BeanUtils.getPropertyDescriptor throws an exception if a field does not have both a getter and a setter defined and that breaks the logic flow of this piece of code. I understand that this is because it expects the class to adhere to the Java bean spec which requires getters/setters... however in this case the classes don't necessarily do so (they're not strictly Java beans). So I suppose this approach won't work. Are there alternatives? 3rd party e.g. Apache commons would be fine.





Aucun commentaire:

Enregistrer un commentaire