Java Reflection checking String fields length

There is a method:

    public List<Field> getAtLeastTenChar(Object o) {

 List<Field> FieldList = new ArrayList<>();
     Class c = o.getClass();
     Field[] mezok = c.getFields();
     for(int i=0; i<mezok.length; i++){

If o has String fields, I want to know, are these strings length reaches 10 character. If yes it puts these fields to the List end at the and returns the List. I think it could be done with reflection, but not sure about how to.


Class<?> objClass = o.getClass();
Field[] fields = objClass.getDeclaredFields();
List<Field> fieldList = new LinkedList<Field>();
for(Field field : fields) { 
    Object value = field.get(o);
    if(value instanceof String)
        if(((String) value).length() > 10){
 return fieldList;

would do what you want, it takes the declared fields checks to see if its instance of String if it is, it checks if the length is greater then 10 then adds the field to a linkedlist.

The code is untested fyi and written on the fly

Leave a Reply

Your email address will not be published. Required fields are marked *