Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reflection, Ignore case when using GetDeclaredField

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

like image 936
GoofyHTS Avatar asked Mar 18 '11 11:03

GoofyHTS


2 Answers

Just use Class.getDeclaredFields() and look through the results performing a case-insensitive match yourself.

like image 164
Jon Skeet Avatar answered Oct 04 '22 20:10

Jon Skeet


No, there's no such way. You can get all fields and search through them:

Field[] fields = src.getClass().getDeclaredFields();
for(Field f:fields){
    if(f.getName().equalsIgnoreCase("myfield")){
    //stuff.
    }
}
like image 20
secmask Avatar answered Oct 04 '22 20:10

secmask