Using the assert
statement in combination with the -ea
switch you can verify that the field's name remains the same.
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;
will simply print "We reached this point" while int a = 5;
will show a nice error:
Exception in thread "main" java.lang.AssertionError
at Main.main(Main.java:38)