简体   繁体   English

如何将 object 传递给在 java 中使用反射的方法

[英]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):传入class就可以了(因为你首先要确定你要调用的方法,然后调用它,没有class的参数,你可能得到一个不是你想要的方法重载):

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.要允许方法修改参数,必须传入一个 object。Java 中的对象也是按值传递的,但是,object 的值是一个引用。 So, the effect is that the object is passed in by reference.因此,效果是通过引用传入 object。 ( For more info ) 了解更多信息

With reflection where you are passing the object to the method, you should use Method.invoke .通过反射将 object 传递给方法,您应该使用Method.invoke As you've got a single parameter do this:因为你有一个参数,所以这样做:

method.invoke(this, abcObj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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