Java Reflection, Ignore case when using GetDeclaredField

前端 未结 7 715
不思量自难忘°
不思量自难忘° 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:49

    No, there is no direct way of doing this, however you could create a helper method for doing this. e.g. (untested)

    public Field getDeclaredFieldIngoreCase( Class clazz, String fieldName ) throws NoSuchFieldException {
    
            for( Field field : clazz.getDeclaredFields() ) {
                if ( field.getName().equalsIgnoreCase( fieldName ) ) {
                    return field;
                }
            }
            throw new NoSuchFieldException( fieldName );
    }
    

提交回复
热议问题