我有类这样的事情
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);