mercredi 21 octobre 2020

How to cast "Object" to an unknown custom data type/class object?

I have a function that returns data type 'Object'.

public Object myMethod(){}

The returned object could be one of many different objects i've defined. For example lets say it returns a objectX.

The place where the function is called and thus we returned back to does

objectX tmp = methodThatReturnsSomeObject();

This works fine. Regardless of what object i return, as long as i cast the returned object it into the correct object. in this case:

objectX tmp = (objectX)methodThatReturnsSomeObject();

My problem is that this function is being used in an environment with a bunch of reflection going on. Im iterating through all the attributes of a class using

Field[] atts = differentObj.getClass().getDeclaredFields(); 
att[i].set(differentObj, val);
//where val is (TYPE of att)methodThatReturnsSomeObject()

i dont necessarily know what kind of object tmp will be because at different points of the iteration it could be an int, String, or another custom object.

Is there some way i can say "whatever class tmp currently is, cast the return of methodThatReturnsSomeObject() into that?

Help would be greatly appreciated





Aucun commentaire:

Enregistrer un commentaire