简体   繁体   中英

How to pass an object to a method using reflection in java

I am working on some code which takes a string input dynamically, so i chose reflection as i didnt find any other better approach for it,

My current code:

Class xyzClass = Class.forName("com.example.Xyz");

Object abcObj =  abcService.generateAbcObj("some string input");
Method method = xyzClass.getDeclaredMethod("add", abcObj); // i want to pass this abcObj to this declared method add but getDeclaredMethod takes class as a parameter

Can anybody suggest way to do in reflection as i want it in a dynamic way or any other way to achieve it in a better sense?

Just pass the class (because you first has to identify the method you want to call, and then call it, and without the class of the parameters, you could get a method overloading that is not the one you want):

Method method = xyzClass.getDeclaredMethod("add", abcObj.getClass());

and then you can invoke it:

method.invoke(/*instance of com.example.Xyz on which you want to call add*/, abcObj);

To allow a method to modify an argument, you must pass in an object. Objects in Java are also passed by value, however, the value of an object is a reference. So, the effect is that the object is passed in by reference. ( For more info )

With reflection where you are passing the object to the method, you should use Method.invoke . As you've got a single parameter do this:

method.invoke(this, abcObj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM