开发者

call function based on string android

i have class something like this

class MClass
{
private int mem1,mem2,mem3.......;
public int getmem1()
{
return mem1;
}
public int getmem2()
{
return mem2;
}

......

Now I want something like this :

public int getAttr(String attr)
{
if (attr=="mem1")
return mem1;
elseif (attr=="mem2")
return mem2;
.....

How do I implement getAttr for 1000s of att开发者_运维知识库r ?

Please don't ask me to make mem as array.. that is not possible due to other parts of program.


Use reflection. Reflection

This will allow you to call any public method at runtime using the name of the method as a String.

Class c = Class.forName("MyClass");
Method m = c.getMethod("get"+arg);
return (Integer) m.invoke(this);


I suggest you create a Map<String, Integer> attrMap and do

public int getAttr(String attr) {
    return attrMap.get(attr);
}


You create a Map<String,Object>. As key you use the attr, as value the values.

class MyCall {

    private final Map<String,Object> map = new HashMap<String,Object>();

    public Object getAttr(String attr) {

        return map.get(attr);

    }
}

If the values will be always integers, then you can replace the generic parameter Object with Integer.

public int getAttr(String attr)  {

   if(map.contains(attr)) {
    return map.get(attr).intValue();
   } else {
    reutrn ERROR_CODE; //As error or throw exception
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜