[ACCEPTED]-Java Reflection, Ignore case when using GetDeclaredField-reflection
Just use Class.getDeclaredFields()
and look through the results performing 1 a case-insensitive match yourself.
No, there's no such way. You can get all 1 fields and search through them:
Field[] fields = src.getClass().getDeclaredFields();
for(Field f:fields){
if(f.getName().equalsIgnoreCase("myfield")){
//stuff.
}
}
The only way I see is to iterate over all 2 declared fields and compare the names case-insensitively 1 to the field name you are looking for.
Get a list of all declared fields and manually 2 go through them in a loop doing a case insensitive 1 comparison on the name.
No, there is no direct way of doing this, however 2 you could create a helper method for doing 1 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 );
}
I don't mean to necro this thread but if 8 you used any of the methods above inside 7 a loop your performance will be awful. Create 6 map beforehand
first take the item your search 5 for to uppercase
item.getKey()
now create a map that has 4 the uppercase version and the true fieldnames
Map<String, String> fieldNames = Arrays.asList(clazz.getDeclaredFields()).stream().collect(Collectors.toMap(t -> t.getName().toUpperCase(), f->f.getName()));
now 3 use that to grab the true fieldname
Field field = clazz.getDeclaredField(fieldNames.get(key));
I would 2 say always create such a map, always consider 1 performance when it comes to reflection.
Best to try to get field with fieldName 2 if does not exist then loop through list 1 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);
}
}
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.