Martin Lehmann
Martin Lehmann

Reputation: 794

Can I aggregate, proxy, or imitate @SuppressWarnings in Java?

I use Spring to build a ModelMap, which is rendered and then parsed by Mustache. For this reason, I have some classes that only exist to wrap data for Mustache's convenience.

These classes have fields and methods that are never used in the code, but are in fact used by Spring (and, in turn, Mustache). I want to explicitly state that this is intentional by annotating the class with a custom annotation @ForMustache that looks like this:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface ForMustache {
}

My goal is basically a fancy way of saying @SuppressWarnings("unused") // For Mustache.

I attempted to annotate ForMustache with @SuppressWarnings("unused"), but its effects apply inside my annotation instead of being propagated to the type annotated with @ForMustache.

Can I proxy or imitate @SuppressWarnings("unused") with another annotation?

Upvotes: 4

Views: 433

Answers (1)

zapl
zapl

Reputation: 63955

The @SuppressWarnings annotation is meant for the compiler and other compile time tools that work directly on the source files.

It is also specified as

@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings { ...

meaning it's not supposed to be available anymore at runtime. This means that even springs meta-annotation aware processing can't see it anymore.

Given enough time, you could build an annotation processor that, during compile-time, transforms a custom @ForMustache annotation into a @SuppressWarnings so the compiler can pick it up. In similar fashion Lombok can turn

@Data
class Foo {
    private final String value;
}

into a) code that compiles and doesn't complain about no assignment to a final field and b) it wouldn't generate a warning because it generates a public getter for the field. Those can only be assumed to be used / they are usable from places outside the compiler's reach.

Besides putting @SuppressWarnings everywhere, your only chance is to remove the condition that causes the warning.

  • Disable the check with a compiler option
  • add public getters or other code so the fields are used (with lombok for example)
  • hook into the compile process.

Upvotes: 3

Related Questions