android反射增强for循环

时间:2014-02-27 09:30:08

标签: android reflection

我知道有关反思的一些事情,因为我读过这篇文章:call function based on string android

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

我正在使用这样的增强型for循环:

int check = 0,check2=0;
        for(PostValue post : helper.posts)
        {
                          //Name method with a String 
            if(category.equals(post.getMethodFromStringHere()))
            {
                check++;
            }
        }

所以我想要的是我可以从上面的if中的字符串中获取方法。

提前致谢。

如果您需要更多信息,可以提出,

编辑:

try {
        int check = 0,check2=0;
        Class<?> postValueClass = Class.forName("PackageName.PostValue");
        Method m = postValueClass.getMethod("get"+category);
        for(PostValue post : helper.posts)
        {
            String response;
            response = (String) m.invoke(post);

            if(category.equals(response))
            {
                check++;
            }

1 个答案:

答案 0 :(得分:0)

这样的事情可以胜任这项工作。我没有测试过!!你可能需要施放一些物体。

Class postValueClass = Class.forName("PostValue");
Method getMethodFromStringHereMethod = postValueClass.getMethod("getMethodFromStringHere");

int check = 0;
int check2 = 0;
for(PostValue post : helper.posts)
{
  Boolean response = (Boolean) getMethodFromStringHereMethod.invoke(post);
  if (response.getBooleanValue())
  {
    check ++;
  }
}