I ran into a simple issue naively trying to do this:
public void someMethod(){
int x = 0;
...
@SuppressWarnings({"rawtypes", "unchecked"})
x = ((Comparable)lhs).compareTo(rhs);
...
}
This is illegal and has to be rephrased to compile:
public void someMethod(){
...
@SuppressWarnings({"rawtypes", "unchecked"})
int x = ((Comparable)lhs).compareTo(rhs);
...
}
I have traced the issue down to ElementType : a statement doesn’t seem to be a valid program element. This is rather confusing – I thought that a statements is something like a supertype of all programming elements.
-
Is there a theoretical or a technical reason for the restriction of valid elements?
-
Could it be done differently – i.e. supposed I could supplant
ElementTypewith my own class and master the rippling changes, could I annotate any statement?
If you look at the Javadoc for
@SuppressWarningsyou’ll see the answer: its declared targets areIn other words, it cannot be legally applied to a statement. It can, however, be applied to a variable declaration. It has nothing to do with whether a statement is a program element; it is basically because this annotation applies only to declarations of things.
Furthermore, if you look at the Javadoc for the enumeration that describes things that can have annotations, statements and expressions are not among the choices. In general, annotations can be applied to declarations of things, not to bits of code.
The theoretical reason for this is just that annotations are stored as properties of individual items declared in the class file. Statements don’t qualify; by the time your code is compiled, statements have ceased to exist. There is only a stream of bytecode, and the only reminder of the statements it came from are the (optional) line number tables. To deal with this, they’d need to add a new attribute to the class file to reference the individual bytecodes, as in this proposal, and deal with a number of complexities that arise as a result.