2012-03-14 106 views
0

我想看看是否可以避免长时间切换,或者如果通过将某些字符串直接转换为对象名称来阻止。例如,我有一个名为Example的类,我想[编辑]有多达10个Example1,Example2等类的实例。我可以使用类似:Android:使用字符串代替对象/实例名称

int ExampleNum = 2;  
// can be changed to any 1-10 value corresponding to instances 
    String s = "Example" + String.valueOf(ExampleNum); 

Refresh(s); 

public void Refresh(Example example){ 
... 
} 

因此,我将创建与例2的值的字符串,并将其传递到我的Refresh方法。

我不想一次使用所有实例,而是使用其他方法来更改int ExampleNum,以便当我尝试刷新它时刷新相应的示例实例。

与其说:

if (ExampleNum == 2) 
    Refresh(Example2); 

我会用ExampleNum和字符串使用正确的实例名称;

+0

为什么不把它们放在一个ArrayList中,只是将该位置传递给您的Refresh方法? – zrgiu 2012-03-14 05:23:51

+0

您正在将'String'传递给一个需要'Example'的方法... – 2012-03-14 05:24:57

+0

对不起。我将如何使用方法Refresh(示例示例)以某种方式使用称为Example2的类Example的实例使用String。除了创建Example类实例之外还有其他方法吗? – willmer 2012-03-14 16:45:06

回答

0

为什么不使用磁盘阵列的替代?

Example[] e = null; 
    for(int i=1;i<=10;i++) 
    { 
     e[i] = new Example(); 
     Refresh(e[i]); 
    } 
+0

这是一个例子的数组?这样e [1]会给我例1吗? – willmer 2012-03-14 16:40:16

+0

是!.e [1]将是您的第一个实例,e [2]秒等等...而不是Example1,Example2 ... – 2012-03-15 05:09:03

0

那么,现在,您的代码没有任何意义,因为您将String传递给Refresh,该代码将Example对象作为参数。

不过,如果你问如何创建琴弦例1,例2,例... 10,你可以这样做:

for (int i = 1; i <= 10; i++) { 
    s = "Example" + i; 
    refresh(s); // assuming this takes a string 
}