samedi 17 décembre 2022

How to efficiently access private fields of object instead of Reflection

I have a use case where in I want to filter out results based on the input I receive from the user.

e.g.

Class Clazz 
   private field x;
   private field y;
   private field z;

In request I'll receive 2 values which field to filter on and what should be it's desired value

e.g.

request : 
   field      : x //
   fieldValue : "123"

So I used Reflection to find which field I need to be filtering on and applied lambda operation to get the desired result

    final Clazz obj = new Clazz(x: "123",y: "abc", z: "pqr");

    final Field requestedAttribute = randomMerchantDetails.getClass().getDeclaredField(request.getAttribute().toString());

    final String output = requestedAttribute.get(obj)

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





Aucun commentaire:

Enregistrer un commentaire