使用java反射在循环中调用编号的函数名称
我有一个问题: MyFirstClass.java
public class MyFirstClass{
String strParam;
MySecondClass secClass;
//getters and setters
}
MySecondClass.java
public class MySecondClass{
String p1Param;
String p2Param;
String p3Param;
String p4Param;
//setters and getters
}
TestClass.java
public void doProcessing(MyFirstClass pObj){
for(int i=0;i<3;i++){
System.out.println() ;
//###question is here
}
我想使用java反射并通过向 g 提供参数来调用 for 循环中的 pObj.getP**Param() 方法
Method m= cls.getMethod("getP"+(i+1)+"Param");
pObj.getSecClass.[ invokeMethod m ]
如何使其成为可能。 我不想使用 p*Params 数组。
提前致谢。
i have a problem as :
MyFirstClass.java
public class MyFirstClass{
String strParam;
MySecondClass secClass;
//getters and setters
}
MySecondClass.java
public class MySecondClass{
String p1Param;
String p2Param;
String p3Param;
String p4Param;
//setters and getters
}
TestClass.java
public void doProcessing(MyFirstClass pObj){
for(int i=0;i<3;i++){
System.out.println() ;
//###question is here
}
I want to use java reflection and call the pObj.getP**Param() methods in for loop by providing the parameters to g
Method m= cls.getMethod("getP"+(i+1)+"Param");
pObj.getSecClass.[ invokeMethod m ]
How it can be made possible.
I don't want to use array of p*Params.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您确定这是您需要的吗?对我来说,您的代码似乎是当前在每项任务中滥用反射趋势的典型示例。为什么不使用数组或映射来存储属性
p[0-9]+Param
。阵列的发明正是为了做到这一点。它们提供了一系列按数字索引的变量。
Are you sure this is what you need? For me, your code seems to be a typical example of the current trend of abusing reflection for every task. Why don't you use arrays or maps to store the properties
p[0-9]+Param
.Arrays were invented to do exactly that. They provide a range of variables, indexed by numbers.
你快到了。一旦有了
Method
对象,只需像这样调用它即可:请注意,此类反射游戏可能会导致难以掌握且复杂的代码,从而难以维护。如果您告诉我们编号参数代表什么,那么我们可以提供更好的解决方案(可能是
List
的单个参数?)。You're almost there. Once you have the
Method
object, just call it like this:Note that such reflection games can lead to hard-to-grasp and complicated code that can be hard to maintain. If you told us what the numbered parameters represent, then we could provide a better solution (possibly a single parameter that is a
List<String>
?).像这样:
Like this: