shriram shriram - 1 month ago 8
Java Question

how to change method name dynamically in loop in java

I have a bean class and i want to fetch MediaContentType0, MediaContentType1, MediaContentType2, MediaContentType3 in a loop
i have get json string and convert it into java class using gson

Gson gson=new Gson();
CommonBean commonBean=gson.fromJson("JsonString",CommonBean.class)
for(int i=0;i<numberOfMedia;i++)
{
commonBean.getMediaUrl0();
commonBean.getMediaUrl1();
commonBean.getMediaUrl2();
//but i want it to fetch dynamically by iTh element.
like-
commonBean.getMediaUrl+i+();


How Could this possibe? Please Suggest. Thanks
}

mybean class is following :-
public class CommonBean {
public String to;
public String from;
public String body;
public String numMedia;
public String MediaContentType0 ;
public String MediaContentType1 ;
public String MediaContentType2 ;
public String MediaContentType3;
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}

public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getNumMedia() {
return numMedia;
}
public void setNumMedia(String numMedia) {
this.numMedia = numMedia;
}
public String getMediaContentType0() {
return MediaContentType0;
}
public void setMediaContentType0(String mediaContentType0) {
MediaContentType0 = mediaContentType0;
}
public String getMediaContentType1() {
return MediaContentType1;
}
public void setMediaContentType1(String mediaContentType1) {
MediaContentType1 = mediaContentType1;
}
public String getMediaContentType2() {
return MediaContentType2;
}
public void setMediaContentType2(String mediaContentType2) {
MediaContentType2 = mediaContentType2;
}
public String getMediaContentType3() {
return MediaContentType3;
}
public void setMediaContentType3(String mediaContentType3) {
MediaContentType3 = mediaContentType3;
}
}


Please suggest how to fetch these element dynamically using getter method?

Answer Source

You can use the Java Reflection API

for(int i=0;i<numberOfMedia;i++) {
  try {
    Method getterMethod = commonBean.getClass().getMethod("getMediaUrl"+i);
    getterMethod.invoke(commonBean);
  } catch(Exception e) {}
}