Java Reflection, Ignore case when using GetDeclaredField

前端 未结 7 673
不思量自难忘°
不思量自难忘° 2021-01-18 05:08

Let\'s say I have a class with a string field named \"myfield\", and use reflection to get the field, I\'ve found that Object.getClass().getDeclaredField(\"myfield\");

7条回答
  •  南笙
    南笙 (楼主)
    2021-01-18 05:59

    Best to try to get field with fieldName if does not exist then loop through list of fields

    public static Field findFieldIgnoreCase(Class clazz, String fieldName) throws SecurityException, NoSuchFieldException {
        try {
            return clazz.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                if (field.getName().equalsIgnoreCase(fieldName)) {
                    return field;
                }
            }
            throw new NoSuchFieldException(fieldName);
        }
    }
    

提交回复
热议问题