Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 attr ?

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

like image 549
Gaurav Shah Avatar asked Aug 25 '26 08:08

Gaurav Shah


1 Answers

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);
like image 167
John B Avatar answered Aug 27 '26 23:08

John B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!