gpt4 book ai didi

java - 反射(reflection):这个成员变量是否对应这个Field

转载 作者:搜寻专家 更新时间:2023-11-01 03:52:00 25 4
gpt4 key购买 nike

假设我有一个带有成员变量 int c 的类。假设我还有一个 Field f。我想检查 f 是否代表 c。我能做到:

f.getName().equals("c")

但我正在寻找一种解决方案,如果我要重命名 c,编译器会以某种方式提醒我。类似于 f == c.getField()

我的猜测是没有办法做到这一点,但我想确认一下!

最佳答案

结合使用 assert 语句和 -ea 开关,您可以验证字段名称是否保持不变。

"Programming With Assertions" guidelines 之后我们可以推断这是使用它们的适用情况:

Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors.

异常用于捕获异常行为,断言用于验证不变的假设。

话虽这么说:从问题描述中不清楚您的设置到底是什么样子,但这段代码将按照我的解释方式运行:

public class Main {
int c = 5;

public static void main(String[] args) {
Field f = null;
try {
f = ReflectionTest.class.getDeclaredField("c");
} catch (NoSuchFieldException | SecurityException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
return;
}

assert hasMember(f);

System.out.println("We reached this point");
}

private static boolean hasMember(Field f) {
for (Field localField : Main.class.getDeclaredFields()) {
if (localField.getName().equals(f.getName())) {
return true;
}
}

return false;
}
}

class ReflectionTest {
int c = 10;
}

使用 int c = 5; 将简单地打印 "We reached this point"int a = 5; 将显示一个很好的错误:

Exception in thread "main" java.lang.AssertionError
at Main.main(Main.java:38)

关于java - 反射(reflection):这个成员变量是否对应这个Field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23891624/

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