0

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

Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73
Hrishikesh
  • 356
  • 2
  • 11
  • For ReflectASM there's this small hint in the doc: "Private members can never be accessed." That's why it does not work. You could build your class as a java.lang.reflect.Proxy class so that you could store the data in a Map maybe, but then the access methods are not that efficient. Here a more comprehensive answer on the whole thing: https://stackoverflow.com/questions/19557829/faster-alternatives-to-javas-reflection – Janos Vinceller Dec 17 '22 at 07:49
  • 2
    If you consider that Reflection “should be avoided”, it doesn’t make much sense to ask for a 3rd party Reflection solution. It’s still Reflection with all consequences regarding stability and security. You should sanitize external input instead of allowing it to access arbitrary private fields. And if you have to limit the input to the permitted fields anyway, you can handle the permitted cases directly, `String fieldValue = switch(attribute) { case "x" -> return getX(); case "y" -> return getY(); case "z" -> return getZ(); default -> throw new IllegalArgumentException(); };` Fast and reliable – Holger Dec 19 '22 at 09:40

0 Answers0