I have a use case where in I want to filter out results based on the input I receive from the user.
My data object looks like this:
class Data {
Data(String x, String y, String z) {
// setting the private fields
}
private String x;
private String y;
private String z;
}
In the request I'll receive 2 values which field to filter on and what should be it's desired value
record Request(String attribute, String value);
Request request = new Request("x", "123");
So I used Reflection to find which field I need to be filtering on and applied lambda operation to get the desired result
Data data = new Data("123", "abc", "pqr");
Field requestedField = Data.getClass().getDeclaredField(request.attribute());
requestedField.setAccessible(true);
String fieldValue = requestedField.get(data)
// filtering can happen here
But since Reflection is not an efficient way of doing this and it should be avoided, is there any other way to do this?
Open to 3P libraries also.
I tried using ReflectASM
but I couldn't access the private fields.
Any efficient approach for solving this would be appreciated