user1300214
user1300214

Reputation:

Is it possible to change method visibility using Java annotations?

IntelliJ greys out some functions which I'm using in a Reflection library. I would like to stop them being greyed out by annotating e.g. with @MyAnnotation. But so far I cannot find a way to do this. So far my custom annotation looks like this:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

}

Is there a default annotation I can add to my own annotation that will stop IntelliJ greying out my annotated methods?

I noticed JavaFX does not grey out functions with the @FXML annotation,

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface FXML {
}

but I cannot see anything there that I'm not already using.

Upvotes: 1

Views: 361

Answers (1)

Peter
Peter

Reputation: 5224

The unused inspection is an IntelliJ feature and other IDEs may have that feature as well, but there is no real definition what used/unused means.

Furthermore, it's not a language feature and therefore, there is no such language support for defining things in java as "used" or "unused". This is an interpretation of the current code base or better "search scope" if some things are in use.

The fact that a method is used in a test case only could be interpreted as unused for example.

To answer your question. You have 3 different approaches to solve that issue:

  1. Just annotate that declaration with SuppressWarnings("unused")
  2. Using the IntelliJ "Suppress unused warnings if annotated by" feature
  3. Disable unused code inspection

The first approach is the one working for other developers right away and is the most explicit one. This will work in eclipse as well as other IDEs. No need to explain that a declaration annotated with SuppressWarnings("unused") is used outside the current search scope. To make things clear: this may look like a language support for declaring things as used, but that annotation is a hint for developers. @SuppressWarnings is a pure source annotation and won't be available at compile or runtime.

The second approach will only work on your machine except you export the project settings into your code repository as well and other developers uses IntelliJ as well. That approach is explained here: IntelliJ suppress unused warning for API methods

The third one is just .. well.. it's an option.

Next Question: How does that work for @FXML?

I'm not sure, but I guess it's a plugin/IntelliJ feature. The gutter icons that simulates the binding from your class member and methods to that particular element in that jxml file is a feature of that plugin as well.

Upvotes: 1

Related Questions