I was never really strong in reflection and I seem to have stumped on a problem that seems trivial but doesn’t turn out that way. At least for me. I have a bean with a few getters , then in a service I use Reflextion to loop over said methods and at a certain point I end up with the get method I want. I invoke the method to get the value, and now I like to know the name of the field I just asked the value from. There is it where I get stuck.
get method
public String getTest(){ return test }
invoking method by reflection
Object value = method.invoke(jsonObject, new Object[]{});
Now I like to do something like this
String fieldName = method.findTheNameOfTheField();
I find lots of examples to call the getter from the fieldname but nothing on how to do the reverse. Is this even possible without parsing the name of the method and just cutting is and get from the method ?
No, you can’t do this – at least not without analyzing the bytecode itself. Don’t forget that the getter can contain any code. Maybe it doesn’t use a field. Maybe it uses more than one field. Maybe all the properties use a map. Maybe it uses a field, but then changes the result (e.g. copies a list).
You should consider whether a change in your design would remove the need for this in the first place – I can’t think of many cases where it would be a good idea.