Should visible private fields be visible from a nested class if they match the surrounding?

I cleaned up the code and changed all access to the static member so that it would be qualified by the class in which they are defined. This, however, leads to the next problem that puzzles me.

I have a class with a nested class inside. In the annotation of this nested class, I refer to a private static final field in the surrounding class. When doing this without qualification (as in the annotation to class D below), this works. However, when adding a class qualifier (as in the annotation for class C), the compiler reports that the field (v below) is not visible.

public class VisibilityTest { @interface A { int f(); } @A(f = VisibilityTest.v) //fails private static class C { int c = VisibilityTest.v; //works } @A(f = v) //works private static class D { int d = VisibilityTest.v; //works } private final static int v = 5; } 

In both cases, the variable refers to one field, so why is this happening?

+5
source share
2 answers

This compiles with 1.8.0_25 and 1.7.0_45 javac , as it should be. Or both must fail, it will also be consistent.

This seems to be a mistake in processing Eclipse annotations (so you can happily refer to the same constant from regular code), it was reported a long time ago, but there has not been much activity over the past 4 years.

+4
source

See How to specify annotation value from constant java .

Basically, you cannot. Annotation values ​​must be primitives or strings. You cannot refer to a field, personal or otherwise.

-2
source

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


All Articles