mercredi 25 février 2015

Weird static initialization in Java when using Reflection

Given the following code-snippet I get the output "B" and "error":



public class Test {

private static class A {
static final B c = new B();
}

private static class B extends A {
static final B c = A.c;
}

public static void main(String[] args) throws Exception {
for(Class<?> cls : Test.class.getDeclaredClasses()) {
if(cls.getDeclaredFields()[0].get(null) == null) {
System.out.println(cls.getSimpleName());
}
}
if(B.class.getDeclaredField("c").get(null) == null) {
System.out.println("error");
}
}

}


But it gets even more bizarre. If I comment-out the for-loop I get no output - so no error. Also if I access the field B.c directly without reflection before doing the reflection stuff the problem does not occur. Why is that so and how can I fix it?






Aucun commentaire:

Enregistrer un commentaire