2017-08-17 24 views
1

環路動態改變方法名我有一個bean類,我想取MediaContentType0,MediaContentType1,MediaContentType2,MediaContentType3在一個循環 我已經得到JSON字符串,並將其轉換成Java類使用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方法獲取這些元素?

+0

的**反射API **讓你動態調用類的方法(和一堆其他有用的動態的東西)。用法非常簡單,只需從'Common'類開始,例如'commonBean.getClass()',然後就可以訪問一些有用的方法。 – Zabuza

+0

已經有問題可以參考下面的帖子。 [最佳方式調用getter-by-reflection](https://stackoverflow.com/questions/2638590/best-way-of-invoking-getter-by-reflection) –

回答

4

您可以使用Java Reflection API

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

urielSilva: - 什麼是getterMethod in下面的語句getterMethod = commonBean.getClass()。getMethod(「getMediaUrl」+ i); – shriram

+0

已更新,對不起:) – urielSilva

+0

urielSilva: - 類型Method中的方法invoke(Object,Object ...)不適用於arguments()。爲什麼這個沒有參數的調用方法getterMethod.invoke();它會導致編譯時錯誤。 – shriram