简体   繁体   English

反射:此成员变量是否与此字段对应

[英]Reflection: does this member variable correspond to this Field

Suppose I have a class with a member variable int c . 假设我有一个带有成员变量int c Suppose I also have a Field f . 假设我也有一个Field f I want to check whether f represents c . 我想检查f是否代表c I can do: 我可以:

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

but I'm looking for a solution such that if I were to rename c , the compiler would alert me in some way. 但我正在寻找一个解决方案,如果我要重命名c ,编译器会以某种方式提醒我。 Something like f == c.getField() . f == c.getField()类的东西。

My guess is that there is no way to do this, but I'd like to confirm! 我的猜测是没有办法做到这一点,但我想确认一下!

Using the assert statement in combination with the -ea switch you can verify that the field's name remains the same. assert语句与-ea开关结合使用,可以验证字段名称是否保持不变。

Following the "Programming With Assertions" guidelines we can deduce that this is an applicable situation to use them: 按照“使用断言编程”指南,我们可以推断出这是适用的情况:

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. 通过验证布尔表达式确实为真, 断言确认了您对程序行为的假设 ,增加了程序没有错误的信心。

Exceptions are used to catch exceptional behaviour, assertions are used to verify invariant assumptions. 异常用于捕获异常行为,断言用于验证不变的假设。

That being said: it was unclear from the problem description how your setup exactly looks like but this snippet will act the way I interpret it: 话虽如此:从问题描述中不清楚你的设置是如何看起来的,但这个片段将按照我的解释方式行事:

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;
}

Using int c = 5; 使用int c = 5; will simply print "We reached this point" while int a = 5; 只需打印“我们达到了这一点”int a = 5; will show a nice error: 会显示一个很好的错误:

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

There are no field literals like there are class literals. 没有像文字一样的字段文字。 That basically means that the only way you can refer to a field is through a String value of its name. 这基本上意味着您可以引用字段的唯一方法是通过其名称的String值。 You won't be able to get IDE refactoring capabilities for fields, which I assume is why you want this. 您将无法获得字段的IDE重构功能,我认为这就是您想要这样做的原因。

public class Example {} ==> public class Refactored
... 
Example.class ==> Refactored.class // would cause compiler error if wasn't changed

You'll need to do this check at runtime, one way or another. 您需要在运行时以这种或那种方式进行此检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM