Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Java annotation for warnings - @NonOptimal

Is there something special to the @Deprecated annotation that I cannot reproduce?

I need to create an annotation similar to @Deprecated to produce warnings in Eclipse and also at build time. When I mark a method as @Deprecated I get nice warnings. For example, if I have an old method (that I may still keep for compatibility reasons):

@Deprecated
public List<Account> getClientAccounts(final int clientId) {
  // Implement search...
}
  • Then, if I try to use it in Eclipse I can see it strikethrough, and a yellow icon in the left bar:

    enter image description here

  • Also when building I can see the:

    [WARNING] app1/src/test/java/com/app1/MyApp.java: app1/src/test/java/com/app1/MyApp.java uses or overrides a deprecated API.

Now, depending on external factors I cannot control (e.g. absence of database indexes) some methods are not optimal, and I would like to clearly mark them as such... with my brand new @NonOptimal annotation. I need to add visibility to the problem. So far I have:

@Retention(RUNTIME)
@Target(METHOD)
// What else here?
public @interface NonOptimal {
}

How can I create this annotation?

like image 733
The Impaler Avatar asked Aug 19 '20 15:08

The Impaler


2 Answers

I wish I could extend Deprecated, but no can do.

After reading about this quite a bit I ended up with an ugly workaround. It works, though I don't like it.

I decided to mark the bad methods with both the @Deprecated and @NonOptimal annotations. It's conceptually wrong (the methods are not actually deprecated) but it works well out of the box. No need to develop an overkill Eclipse plugin:

  • The @Deprecated annnotation bugs developers all around the place (in Eclipse and when building), and that's a good thing.

  • The @NonOptimal annotation provides details on why this is a bad method to use.

Ugly but works. As of now Eclipse does not provide any better option.

Note: to make things worse, the NonOptimal annotation does not work well in Maven when using toolchains: warnings go silent, disappear, nada... Therefore, AnnotationProcessors are kind of useless in the end.

like image 153
The Impaler Avatar answered Oct 27 '22 00:10

The Impaler


@TheImpaler This is actually not a true answer for your problem, but some time ago I came across the Google Annotations Library (a.k.a. gag) while using Zalando's Problem API.

This library provides a great number of custom annotations that, in some cases, can be used to instrument your actual code by using a ASM and a custom java agent.

Maybe it can give you some ideas regarding your actual issue.

The project is no longer maintained but there is a fork in Github.

like image 32
jccampanero Avatar answered Oct 26 '22 23:10

jccampanero