gpt4 book ai didi

java - 如何获取嵌套字段

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:10:23 24 4
gpt4 key购买 nike

我是反射的新手,我正在尝试获取嵌套字段。总结我有以下类(class):

public class Agreement{

private Long id;

private String cdAgreement;

private Address address;

//Constructor getter and setter

}

public class Address{

private Long id;

private String description;

//Constructor getter and setter

}

现在我想获取描述字段,然后我写了这段代码:

Agreement agreement = new Agreement();
Class c = agreement.getClass();
Field f = c.getDeclaredField("address.descritpion");

但不起作用,我得到以下异常:

java.lang.NoSuchFieldException: address.descritpion
at java.lang.Class.getDeclaredField(Class.java:1948)

我哪里做错了?

最佳答案

当前的问题是没有字段具有名称“address.description”(它甚至不是字段的有效名称)。

您必须先获取地址字段,访问它的类,然后从那里获取嵌套字段。为此,请使用 getType():

Agreement agreement = new Agreement();
Class c = agreement.getClass(); // Agreement class
Field f = c.getDeclaredField("address"); // address field
Class<?> fieldClass = f.getType(); // class of address field (Address)
Field nested = fieldClass.getDeclaredField("description"); // description field

你也可以在没有局部变量的情况下链接调用:

Field nested = c.getDeclaredField("address").getType().getDeclaredField("description");

关于java - 如何获取嵌套字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23514190/

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