从大量文本字段中获取和打印数据的最佳方法?
我正在尝试找出从大约 60 个文本字段读取数据然后将其打印在空格行中的最佳方法。
例如
System.out.println(field1.getText() + " " + field2.getText());
问题是,我不想有大量的 getText() 方法。
所以我的主要问题是,是否有一种更简单、也许更好(性能方面)的方法来做到这一点?
图像: 我的文本字段
I'm trying to figure out the best way to read data from around 60 text fields and then print it in a spaced line.
For example
System.out.println(field1.getText() + " " + field2.getText());
The thing is, I don't want to have a crap load of getText() method.
So my main question is, is there an easier and perhaps better (performance-wise) way to do this?
Image:
my text fields
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 StringBuilder 而不是字符串连接以获得更好的性能:
如果您的字段存储在集合中,您可以迭代该集合而不是调用每个单独的字段:
You could use StringBuilder instead of string concatenation for better performance:
And if your fields were stored in a collection you could iterate over that collection instead of calling each individual field:
我想不出任何其他性能更好的方法。
首先,
可以使用 for 循环迭代它们。
其次,
I couldn't think of any other performance wise better method.
Firstly,
could iterate them using a for loop.
Secondly,
将字段添加到数组或集合中,然后在 for-each 循环中迭代它们,打印输出。
在类上使用反射,通过某种命名约定来标识字段,例如正则表达式
textField.+
编写自己的注释,使其在运行时可保留,并对要访问的每个字段进行注释,然后使用反射来迭代类字段,检查注释,并打印文本字段的值(如果有) 编写您自己的注释
如果有良好的命名约定/模式,2. 是最好的。 3.有点重,但是非常精确和灵活。 1.也是一种快速而简单的破解方法。
Add your fields to an array or collection, then iterate over them in a for-each loop, printing out the output.
Use reflection over the class, to identify the fields by some naming convention, like the regular expression
textField.+
Write your own annotation, make it retainable in runtime, and annotate every field you want to visit, then use reflection to iterate over class fields, checking for the annotation, and printing the value of the text field if it has the annotation attached.
With good naming convention/pattern, 2. is best. 3. is a bit heavyweight, but very precise and flexible. 1. is a quick and easy hack too.
您可以尝试使用反射。但从性能角度来看,它会更慢:
这既快又脏,从长远来看,您最好将文本字段放入适当的数据结构(例如列表或地图)中,然后简单地对其进行迭代。
You could try using reflection. Performance-wise it will be slower though:
This is quick and dirty and in the long run you will be better off putting your textfields into an appropriate data structure (e.g. List or Map) and simply iterate over it.