使用java反射在循环中调用编号的函数名称

发布于 2024-11-05 06:59:43 字数 732 浏览 0 评论 0原文

我有一个问题: 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

帝王念 2024-11-12 06:59:43

您确定这是您需要的吗?对我来说,您的代码似乎是当前在每项任务中滥用反射趋势的典型示例。为什么不使用数组或映射来存储属性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.

自在安然 2024-11-12 06:59:43

你快到了。一旦有了 Method 对象,只需像这样调用它即可:

String param = (String) m.invoke(pObj.getSecClass());

请注意,此类反射游戏可能会导致难以掌握且复杂的代码,从而难以维护。如果您告诉我们编号参数代表什么,那么我们可以提供更好的解决方案(可能是 List 的单个参数?)。

You're almost there. Once you have the Method object, just call it like this:

String param = (String) m.invoke(pObj.getSecClass());

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>?).

ˇ宁静的妩媚 2024-11-12 06:59:43

像这样:

Object result = m.invoke(pObj.getSecClass)

Like this:

Object result = m.invoke(pObj.getSecClass)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文