从嵌套对象中功能检索String值

时间:2019-02-20 21:30:19

标签: java

我有一个n嵌套对象,并且尝试动态并顺序地检索此对象的第n个字符串值。这是一些使用Lombok批注的代码:

public static void main(String[] args) {
    Details details = Details.builder()
            .primaryAddress(Address.builder()
                    .line1("1 John Street")
                    .town("John Town")
                    .country("UK")
                    .postcode("AB12CD")
                    .build())
            .secondaryAddress(Address.builder()
                    .line1("2 John Street")
                    .town("John Town")
                    .build())
            .build();

    Displayer displayer = new Displayer();
    displayer.addExtractor(Details.class, Details::getPrimaryAddress, Details::getSecondaryAddress);
    displayer.addExtractor(Address.class, Address::getLine1, Address::getLine2, Address::getTown, Address::getCountry, Address::getPostcode);
    displayer.display(details);
}

@Value
@Builder
public static class Details {
    Address primaryAddress;
    Address secondaryAddress;
}

@Value
@Builder
public static class Address {
    String line1;
    String line2;
    String town;
    String country;
    String postcode;
}

public static class Displayer {
    Map<Class<?>, List<Function<?, ?>>> extractors;

    public <T> void addExtractor(Class<T> clazz, Function<T, ?>...functions) {
        this.extractors.put(clazz, Lists.newArrayList(functions));
    }

    public void display(Object object) {
        if (extractors.containsKey(object.getClass())) {
            List<Function<?, ?>> functions = this.extractors.get(object.getClass());
            for (Function<?, ?> function : functions) {
                display(function.apply(object));
            }
            return;
        }

        System.out.println(object.toString());
    }
}

输出应按功能添加到显示器的顺序显示details主地址和辅助地址中的所有内容,但是这种模式存在一些缺陷,我似乎找不到解决方法,即function.apply(object)因为期望capture<?>而不是Object而无法工作的事实,以及递归的事实。

基本上,我应该可以将任何对象传递给我的Displayer类,只要它知道如何处理该对象的成员,它也应该尝试显示那些成员,依此类推。有什么更好的方法可以实现这一目标?

0 个答案:

没有答案