Java Reflection, ignore case when using GetDeclaredField

Let's say I have a class with a string field called "myfield" and use reflection to get the field, I found that Object.getClass().getDeclaredField("myfield"); case sensitive, it will throw a NoSuchFieldException if, for example, I use Object.getClass().getDeclaredField("myfield");

Is there any way? making him ignore the case?

thanks

+4
source share
5 answers
+15
source

No, there is no such way. You can get all the fields and search for them:

 Field[] fields = src.getClass().getDeclaredFields(); for(Field f:fields){ if(f.getName().equalsIgnoreCase("myfield")){ //stuff. } } 
+3
source

No, there is no direct way to do this, however you can create a helper method for this. e.g. (Unverified)

 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 ); } 
+3
source

The only way I can see is to iterate over all declared fields and compare case insensitive names with the name of the field you are looking for.

+2
source

Get a list of all declared fields and manually go through them in a loop, making a case-insensitive name comparison.

+2
source

Source: https://habr.com/ru/post/1344254/


All Articles