2016-03-01 58 views
0

如何將ArrayList類型的元素傳遞給方法?我天真的嘗試沿着下面的路線。如何將ArrayList類的類元素傳遞給方法

public double example(ArrayList<CMyType> list, String type){ 

    double out = list.get(0).type // type should be a placeholder for one of the variables which I defined in CMyType 
    return out; 

} 

public class CMyType { 
    public double var1; 
    public double var2; 
} 

回答

1

你想在這裏做的事情:

double out = list.get(0).type // type should be a placeholder for one of 

也不是沒有可能使用反射,這樣的:

public double example(ArrayList<CMyType> list, String type) { 
    CMyClass obj = list.get(0); 
    Field field = obj.getClass().getDeclaredField(type); 
    Object objOut = field.get(obj); 
    // you could check for null just in case here 
    double out = (Double) objOut; 
    return out; 
} 

你也可以考慮修改你的CMyType類看起來像這樣:

class CMyType { 
    private double var1; 
    private double var2; 

    public double get(String type) { 
    if (type.equals("var1")) { 
     return var1; 
    } 
    if (type.equals("var2")) { 
     return var2; 
    } 

    throw new IllegalArgumentException(); 
} 

,然後從你的代碼是這樣稱呼它:

public double example(ArrayList<CMyType> list, String type) { 
    CMyClass myobj = list.get(0); 
    return myobj.get(type); 
} 

更好的解決辦法是使用Map<String, Double>CMyType這樣的:

class CMyType { 
    private Map<String, Double> vars = new HashMap(); 

    public CMyType() { 
    vars.put("var1", 0.0); 
    vars.put("var2", 0.0); 
    } 

    public double get(String type) { 
    Double res = vars.get(type); 
    if (res == null) throw new IllegalArgumentException(); 
    return res; 
} 
+0

太棒了!謝謝。這工作! – Christian

0

爲什麼不

public double example(ArrayList<CMyType> list, String type){ 
    double out = list.get(0).type // type should be a placeholder for one of the variables which I defined in CMyType 
    return out; 
} 

public class CMyType { 
    public double var1; 
    public double var2; 
} 

public invocationTest() { 
    ArrayList<CMyType> arrayList = new ArrayList<CMyType>(); //or populate it somehow 
    return myExample(arrayList.get(0)); 
} 

public double myExample(CMyType member, String type){ 
    double out = member.type; 
    return out; 
} 
+0

我認爲他希望使用'type'作爲'CMyType'字段的字段名稱 – stjepano

+0

啊,那麼他需要使用反射來通過String類型訪問成員。 – Shark

相關問題