gpt4 book ai didi

java - 如何在java中的循环中动态更改方法名称

转载 作者:行者123 更新时间:2023-11-29 07:28:58 25 4
gpt4 key购买 nike

我有一个 bean 类,我想在循环中获取 MediaContentType0、MediaContentType1、MediaContentType2、MediaContentType3我得到了 json 字符串并使用 gson 将其转换为 java 类

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

这怎么可能?请建议。谢谢

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

请建议如何使用 getter 方法动态获取这些元素?

最佳答案

您可以使用 Java Reflection API

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

关于java - 如何在java中的循环中动态更改方法名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45737329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com