gpt4 book ai didi

Java反射抓取一个非公共(public)领域

转载 作者:行者123 更新时间:2023-11-29 10:04:06 29 4
gpt4 key购买 nike

我在使用 Java 反射获取类中的字段时遇到问题:

public class CraftLib
{
static List alloyRecipes = new ArrayList();
public static HashSet damageOnCraft = new HashSet();
public static HashMap damageContainer = new HashMap();

public static void addAlloyResult(ur output, Object[] input)
{
alloyRecipes.add(Arrays.asList(new Object[] { input, output }));
}
//file continues

我尝试像这样抓取字段:

try {
Field[] fields = Class.forName("class.path").getFields();
for(Field f : fields) {
System.out.println(f.getName());
} catch (ClassNotFoundException e) {
System.out.println("Damn.");
}
System.out.println(fields.length);

出于某种原因,它只能获取 damageOnCraftdamageContainer 字段,但我真正需要的那个,alloyRecipes,却不是捕获了。我无法编辑第一个文件,那么获取和编辑该字段的最佳方式是什么?

最佳答案

getFields()如果无法访问,则不会为您提供私有(private)、包保护或 protected 字段。

(getFields()) Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object

显然,您的包保护的 alloyRecipes 在您的情况下不可访问。

你需要getDeclaredFields()

(getDeclaredFields()) Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields.

关于Java反射抓取一个非公共(public)领域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14078753/

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