mardi 20 juillet 2021

What's the best way to find the getters of a class

I have a for (Field field : CLASS.getDeclaredFields())

And i want to find if every field in the CLASS have a getter method that returns its value

So i use inside that loop:

List<Field> FieldGettersNotFound = new ArrayList<>();

for (PropertyDescriptor descriptor : Introspector.getBeanInfo(CLASS).getPropertyDescriptors()){

                if (!(descriptor.getReadMethod() != null //if method is no null
 && descriptor.getReadMethod().getParameterTypes().length==0 //if method has no parameters
 && descriptor.getReadMethod().getReturnType().equals(field.getType()))){ //if method returns the same type 
                                                            //as the type of the current field in the loop

                    if (!FieldGettersNotFound.contains(field))
                        FieldGettersNotFound.add(field);

                }

                else FieldGettersNotFound.remove(field);

 }


if (FieldGettersNotFound.size()>0) throw an Exception;

Its seems fine but when it gets in a situation like this, no exception is thrown

public class RandomSituation {

private String Name;
private String LastName;

public String getName(){

    return Name;

}

}

One way of solving this problem is:

(its all the same i just added 1 if in the else)

for (PropertyDescriptor descriptor : Introspector.getBeanInfo(CLASS).getPropertyDescriptors()){

                if (!(descriptor.getReadMethod() != null && descriptor.getReadMethod().getParameterTypes().length==0
                        && descriptor.getReadMethod().getReturnType().equals(field.getType()))){

                    if (!FieldGettersNotFound.contains(field))
                        FieldGettersNotFound.add(field);

                }
                else { 
                    if (descriptor.getReadMethod().getName().equalsIgnoreCase("get"+field.getName()))
                          FieldGettersNotFound.remove(field);

                     }
           }

But some psychopaths may call their method returnName() or something like this

Is there any better way of checking if a class have a getter method for all its fields?





Aucun commentaire:

Enregistrer un commentaire