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 ElementType
with my own class and master the rippling changes, could I annotate any statement?
You can repeat an annotation anywhere that you would use a standard annotation.
Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements. When used on a declaration, each annotation often appears, by convention, on its own line. As of the Java SE 8 release, annotations can also be applied to the use of types.
In GeneralYou can't annotate an object (that exists at runtime only). You just can annotate a declaration or, since Java 8, a type usage (that exists already at compile time).
If you look at the Javadoc for @SuppressWarnings
you'll see the answer: its declared targets are
@Target(value={TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE})
In 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With