“迭代”通过方法
假设我有一个 Java 对象,其中包含以下方法:
public String getField1();
public String getField2();
public String getField3();
public String getField4();
public String getField5();
有没有办法迭代这些方法并像下面的代码一样调用它们?
String fields = "";
for(int i = 1; i <= 5; i ++){
fields += object.(getField+i) + " | ";
}
感谢您即将提出的想法。
Let's say I've got a Java object that's got among others the following methods:
public String getField1();
public String getField2();
public String getField3();
public String getField4();
public String getField5();
Is there a way to iterate through these methods and call 'em like the following code?
String fields = "";
for(int i = 1; i <= 5; i ++){
fields += object.(getField+i) + " | ";
}
Thank you for your upcoming ideas.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请参阅本指南以供参考。
See this guide for reference.
有一种使用反射的方法:
但是:
这个行业充满了糟糕的编码实践的味道!
难道你不能像这样重写所有的
getFieldN()
方法吗?您创建编号方法是在自找麻烦。请记住,反射速度很慢,只有当基于字符串的方法调用对于程序流程绝对重要时才应使用反射。我有时将这种技术用于用户定义的脚本语言,您必须按名称获取方法。这里根本不是这种情况,您的调用是整数索引。因此,您应该保留整数作为参数。
如果这是遗留代码,并且您绝对无法更改此错误编码,那么您最好像上面一样创建一个新方法
getMethod(int)
来包装现有方法,该方法仅委托给编号的getMethodN()
方法。There is a way using reflection:
However:
This business all smells of bad coding practice!
Can't you rewrite all the
getFieldN()
methods like this?You are asking for trouble by creating numbered methods. Remember that reflection is slow and should only be used when String-based method calls are absolutely essential to the flow of your program. I sometimes use this technique for user-defined scripting languages where you have to get a method by name. That isn't the case at all here, your calls are integer-indexed. You should therefore keep the integer as a parameter.
If this is legacy code and you are absolutely unable to change this bad coding, then you might be better off creating a new method
getMethod(int)
as above to wrap the existing methods, that just delegates to the numberedgetMethodN()
methods.为了能够选择特定字段并排序,您应该指定它们,即通过字段名称列表。
To be able to select specific fields and order you should specifiy them i.e. by a list of field names.