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");
is case sensitive, it will throw an NoSuchFieldException
if I for example use Object.getClass().getDeclaredField("MyField");
Is there any way around it? forcing it to ignore case?
Thanks
Get a list of all declared fields and manually go through them in a loop doing a case insensitive comparison on the name.
Best to try to get field with fieldName if does not exist then loop through list of fields
No, there is no direct way of doing this, however you could create a helper method for doing this. e.g. (untested)
I don't mean to necro this thread but if you used any of the methods above inside a loop your performance will be awful. Create map beforehand
first take the item your search for to uppercase
now create a map that has the uppercase version and the true fieldnames
now use that to grab the true fieldname
I would say always create such a map, always consider performance when it comes to reflection.
No, there's no such way. You can get all fields and search through them:
Just use
Class.getDeclaredFields()
and look through the results performing a case-insensitive match yourself.