gpt4 book ai didi

java - 如何使用反射提取某个类型的所有属性?

转载 作者:行者123 更新时间:2023-11-30 03:32:57 27 4
gpt4 key购买 nike

我有许多类,它们可以包含 TranslatableText 类型的一个或多个属性。 。此外,某些类可能具有本身包含此类属性的属性,例如 List<TranslatableText>Map<String, TranslatableText> .

您将如何以有效的方式扫描这些类,同时获取 TranslatableText 的实例在通用集合中?

class Project{
String id;
TranslatableText name;
List<Action> actions;
}

class Action {
String id;
TranslatableText name;
TranslatableText description;
}

// getter & setters omitted

最佳答案

你可以使用这样的循环

// for super classes, use recursion.
for(Field f : obj.getClass().getDeclaredFields()) {
Class type = f.getType();
if (type == String.class || type == TranslatableText.class) {
Object value = f.get(object);
if (value != null)
map.put(f.getName(), value.toString());
}

关于java - 如何使用反射提取某个类型的所有属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28587646/

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