简体   繁体   English

Java中带有标识符变量的对象的“元访问”

[英]“Metaaccess” of Objects in Java With Variables in the Identifiers

I want to access to a certain number of objects in Java without write a lot of code, for example: 我想在不编写大量代码的情况下访问Java中一定数量的对象,例如:

int X;  
for(X=0;X<5;X++){
    jLabelX = /*do something*/
}

Would be something like this: 将是这样的:

When X=0 then jLabel0 is access, X=1 then jLabel1 and so on... X=0访问jLabel0X=1然后访问jLabel1 ,依此类推...

Is there any way of doing this? 有什么办法吗? or i need to specify all the cases 或者我需要指定所有情况

The best way of doing this is to not have variables called jLabel0 , jLabel1 etc in the first place. 最好的方法是首先不要使用名为jLabel0jLabel1等的变量。 Instead, have an array variable (or some other collection): 而是使用数组变量(或其他一些集合):

JLabel[] labels = new JLabel[5];

for (int i = 0; i < labels.length; i++) {
    labels[i] = new JLabel();
    // Whatever

You can get at fields with reflection, but any time I see variables x0 , x1 , x2 etc I shudder - it's a clear indication that a collection of some kind is a better fit. 可以通过反射获得字段,但是任何时候只要看到变量x0x1x2等,我都会感到不寒而栗-这清楚地表明,某种类型的集合更合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM