调用基于Android的字符串函数 [英] call function based on string android

查看:119
本文介绍了调用基于Android的字符串函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类这样的事情

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

......

现在我想是这样的:

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

我要如何attr的1000实现GETATTR?

How do I implement getAttr for 1000s of attr ?

请不要问我做纪念品作为数组..这是不可能的,因为程序的其它部分。

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

推荐答案

使用反射。 反射

这将允许您使用该方法作为一个字符串的名称在运行时调用任何公共方法。

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);

这篇关于调用基于Android的字符串函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆