android/java 概念用单个循环调用所有 getter 方法
我正在做一项作业并陷入困境: 我有一个类,其中有 30 个 getter 和 setter 方法。
public class example{
public String get1(){
return someString1;
}
public String get2(){
return someString1;
}
public String get3(){
return someString4;
}
and so on...
public String get30(){
return someString30;
}
}
现在我想用一个循环调用所有 getter 方法,就像
for(int i= 1; i<=30;i++){
// String total = get1()+get2()+get3()...............
}
我应该做什么?
编辑:我使用反射做到了这一点:
http: //docs.oracle.com/javase/tutorial/reflect/member/methodInitation.html
谢谢 Ricky
I am doing an assignment and stuck at this point:
I have a class in which i have 30 getter and setter method.
public class example{
public String get1(){
return someString1;
}
public String get2(){
return someString1;
}
public String get3(){
return someString4;
}
and so on...
public String get30(){
return someString30;
}
}
Now i want to call all getter method with a single loop like
for(int i= 1; i<=30;i++){
// String total = get1()+get2()+get3()...............
}
what should i do?
Edit: i did it using reflection :
http://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html
Thanks Ricky
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
注释代码是做到这一点的唯一方法。但这是你的设计不正确的征兆。您当然应该拥有一个
String[]
或List
类型的属性,而不是拥有 30 个String
类型的属性。然后你可以这样做:
The commented code is the only way to do that. But this is a symptom that your design is incorrect. Rather than having 30 properties of type
String
, you should certainly have one property of typeString[]
orList<String>
.Then you could do:
如果这些是标准访问器,那么最好使用
List
并执行get(index)
否则反射 hack
现在将帮助循环
If these are the standard accessors then better to go for
List
and doget(index)
else Reflection hack will help
now loop
只需重写示例类中的 toString() 方法,如下所示:
Just override the toString() method in the example class like this:
我使用反射来做到这一点:
http://docs.oracle.com/javase /tutorial/reflect/member/methodInitation.html
I did it using reflection :
http://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html