亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何調用位于另一個實例內部的實例的 getter 方法

如何調用位于另一個實例內部的實例的 getter 方法

哆啦的時光機 2022-07-20 10:29:10
我有一些像下面這樣的課程:@Getter@Setterclass Person{    @JsonProperty("cInfo")    private ContactInformation contactInfo;    private String name;    private String position;}@Getter@Setterclass ContactInformation{    @JsonProperty("pAddress")    private Address address;}@Getter@Setterclass Address{    private String street;    private String district;}我要做的是為 Person 對象編寫一個 Utils 方法,該方法采用一個參數,即 attributeName 作為 String 并返回該屬性的 getter 值。前任:attributeName = name -> return person.getName() attributeName = position -> return person.getPosition() attributeName = cInfo.pAddress.street -> return person.getContactInfo().getAddress().getStreet() attributeName = cInfo.pAddress.district -> return person.getContactInfo().getAddress().getDistrict()下面是我所做的:我遍歷 Person 對象中的所有字段并檢查 attributeName 是否等于 JsonProperty 的名稱或字段的名稱,然后我將返回這個 getter。Object result;Field[] fields = Person.class.getDeclaredFields();for (Field field : fields) {    JsonProperty jsonProperty = field.getDeclaredAnnotation(JsonProperty.class);    if (jsonProperty != null && jsonProperty.value().equals(attributeName)) {        result = Person.class.getMethod("get" + capitalize(field.getName())).invoke(person);    } else {        if (field.getName().equals(attributeName)) {            result = person.class.getMethod("get" + capitalize(field.getName()))                    .invoke(person);        }    }}這僅適用于直接位于 Person 類中的字段,例如:姓名、職位。使用contactInfo 或address 中的字段,我仍然被困在那里。誰能在這里給我一些提示我該怎么做?
查看完整描述

1 回答

?
慕尼黑8549860

TA貢獻1818條經驗 獲得超11個贊

因為路徑喜歡a.b.c與不同的對象相關。所以你需要。按點拆分并為每個令牌調用獲取并將獲得的結果用于下一個令牌


更新:類似:


private static Object invkGen(Object passedObj, String attributeName) throws Exception {

    final String[] split = attributeName.split("\\.");

    Object result = passedObj;

    for (String s : split) {

        if (result == null) {

            break;

        }

        result = invk(result, s);

    }

    return result;

}


private static Object invk(Object passedObj, String attributeName) throws Exception {

    Object result = null;

    final Field[] fields = passedObj.getClass().getDeclaredFields();


    for (Field field : fields) {

        JsonProperty jsonProperty = field.getDeclaredAnnotation(JsonProperty.class);

        if (jsonProperty != null && jsonProperty.value().equals(attributeName)) {

            result = Person.class.getMethod("get" + capitalize(field.getName())).invoke(passedObj);

        } else {

            if (field.getName().equals(attributeName)) {

                result = passedObj.getClass().getMethod("get" + capitalize(field.getName()))

                    .invoke(passedObj);

            }

        }

    }

    return result;

}


查看完整回答
反對 回復 2022-07-20
  • 1 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號