Reflection: Does this member variable match this field

Suppose I have a class with a member variable int c. Suppose I also have Field f. I want to check if presented f c. I can do:

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

but I'm looking for a solution that, if I renamed c, the compiler somehow warned me. Something like that f == c.getField().

I suppose there is no way to do this, but I would like to confirm!

+4
source share
2 answers

Using the operator assertin combination with the switch -ea, you can verify that the field name remains the same.

Programming With Assertions, , :

, , , . , . , , , , .

, .

: , , , :

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; " ", int a = 5; :

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

, . , , , - String . IDE , , .

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

, .

0

Source: https://habr.com/ru/post/1542192/


All Articles