mercredi 1 novembre 2017

Is it possible to use a reflected object as a parameter of a normal method?

I have a question about java reflection. I've got an object using reflection. The underlying Class of this object is not a part of my packages but I can acquire it using object.getClass() . The problem is that I also have a method that expects this object of this Class that i do not have (this method is acquired also with reflection, so I cannot change its implementation). So now I have to use this object as an input for this method.

The main issue here is that when the method tries to use the reflected object as an input it expects, it fails because the method cannot call the reflected objcet's methods in a normal way, but only with method.invoke().

I'm trying this and it really looks very impossible but there is not very much I haven't tried.

Example: Lets call the main object I'm reflecting 'obj'. And 'obj2' the object of which I'm getting the method from.

Class objClass = obj.getClass();
obj = objClass.cast(obj);

Method m = obj2.getClass().getMethod("method1");
Object[] inputs = {obj};
m.invoke(obj2, inputs);

I cannot create a new instance of this class because I need exactly this object(obj1) to pass to the method. So a new instance wont work.

It is very hard for me to explain this. Hope someone can tell me at least if its doable.





Aucun commentaire:

Enregistrer un commentaire