1

I have the following request with these fields:

Payment (Type Payment) -> Parameters (Type Object). I know this Parameters class has these fields:

  • token (String)
  • type (String)
  • cvv (String)

I´m trying to have access to the field token through request.getPayment().getParameters() but I don't really know how to make it work. I found something related to Reflection but I don´t really know how it can work.

I've tried something like but I still don't know howo to fetch this String "token":

 Field field = org.springframework.util.ReflectionUtils.findField(String.class, "token"); org.springframework.util.ReflectionUtils.makeAccessible(field); String token = field.get(request.getPayment().getParameters().????) ???? 
1
  • If the class has these fields then it must provide some way to access them, surely? Commented Aug 6, 2020 at 21:38

1 Answer 1

0

If you sure that you will always have these fields in this generic object, you can just use casting:

class PaymentParameter { String token; String type; String cvv; ... // getters & setters or Lombok stuff } ... var paymentParameters = (PaymentParameters) request.getPayment().getParameters(); 

You can read more about casting here and here.

Please be aware that casting can throw ClassCastException. So you have to cover this case in your code.

The second option is that your request is a JSON string, then you can use Jackson to convert it to the map or object. This topic is covered also on Baeldung.

Sign up to request clarification or add additional context in comments.

2 Comments

I know that, but I don´t want to create a new class if possible.
In that case please check this anwser: stackoverflow.com/a/16172206/1110241

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.