有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何为位于另一个实例内部的实例调用getter方法

我有以下几节课:

@Getter
@Setter
class Person{
    @JsonProperty("cInfo")
    private ContactInformation contactInfo;
    private String name;
    private String position;
}

@Getter
@Setter
class ContactInformation{
    @JsonProperty("pAddress")
    private Address address;
}

@Getter
@Setter
class Address{
    private String street;
    private String district;
}

我要做的是为Person对象编写一个Utils方法,它将一个参数attributeName作为字符串,并返回这个属性的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类中的字段,例如:name、position。由于联系人信息或地址中的字段,我仍然被卡在那里。有人能给我一些提示吗?我该怎么做

谢谢大家!


共 (1) 个答案

  1. # 1 楼答案

    因为像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;
    }