jeudi 4 janvier 2018

Get object instance from Class<*> (Reflection)

Some background - I'm trying to write a generic way of overriding values coming from server, without knowing exactly on which class they should be set. So what I'm doing is:

I look at the key/value I got from the server and then I start looking (iterating) at the "User" object and all of it's fields - if one of the fields matches what I got from server - I need to override it's value.

One of the User fields can be another class by itself like "Settings" and then I need to repeat the iteration on the settings class and so on -until I find a match.

Once I found a match I need to set the value. And here is where my problem is:

Trying to set a method in a class type but I get thrown IllegalArgumentException

target.declaredMethods[1].invoke(target, true)

java.lang.IllegalArgumentException: Expected receiver of type test.reflectiveparser.User$Settings, but got java.lang.Class<test.reflectiveparser.User$Settings>

I realise I need to invoke the method on the instance and not the Class type - but how do I do that if I don't know what class I'm working on until runtime?

(trying to build a generic way of setting values in different classes)





Aucun commentaire:

Enregistrer un commentaire