从数组动态使用getter和Setter方法

时间:2013-07-02 13:22:36

标签: php android

我使用下面的方法通过在php中使用这种类型的动态getter方法来获取值。这有可能在getter方法java或android中获得值吗?

$objects = array("model", "make", "version");
          foreach ($objects as $object) {
              $getter = "get".ucfirst($object);
              if (is_object($iProduct->$getter())) {
                  echo "getvalue"+$iProduct->$getter()
          }

1 个答案:

答案 0 :(得分:2)

你可以用反射来做类似的事情:

String[] objects = { "model", "make", "version" };
Class k = iProduct.class;
String getter;
Method m;
for(int i=0; i<objects.length; i++) {
    try {
        getter = "get" + Character.toUpperCase(objects[i].charAt(0)) + objects[i].substring(1);
        m = k.getMethod(getter, null);
        System.out.println("getvalue" + m.invoke(iProduct));
    }
    catch(NoSuchMethodException ex) {
        //this particular getter doesn't exist
    }
}