Is there a global setting in the Java Compiler to disable deprecation for String.formatted()?

2k Views Asked by At

The method String.formatted() is a new feature in Java 13 introduced together with text blocks and can be used instead of String.format(templateString, replacement1, replacement2, ...).

The compiler issues a jarring warning when using this method because it might be removed again in future versions (but it could also stay).

Is there a way to specifically disable this compiler warning without annotating each usage with @SuppressWarnings("removal") or disabling all deprecation warnings as java compiler parameter?

3

There are 3 best solutions below

0
On

You can add -Xlint:-removal parameter to javac command line and instead of warning you will get a note message per class:

Note: MyClass.java uses or overrides a deprecated API that is marked for removal.

Note: Recompile with -Xlint:removal for details.

I don't think there is an option to specify this just for String.formatted(), it's global.

0
On

Yes, you can suppress warnings bypassing compiler argument. In your case, you can use -Xlint. -Xlint can be used with different properties.

-Xlint Enable all recommended warnings.

-Xlint:all Enable all recommended warnings.

-Xlint:none Disable all warnings.

-Xlint:name Enable warning name. See the section Warnings That Can Be Enabled or Disabled with -Xlint Option for a list of warnings you can enable with this option.

-Xlint:-name Disable warning name. See the section Warnings That Can Be Enabled or Disabled with -Xlint Option for a list of warnings you can disable with this option.

For more info please go through java docs.

0
On

Simple answer: don't do this. If your project cares about deprecation warnings, you probably shouldn't be using preview features like String.formatted().

In fact, the method will be removed in Java 14, at least if you don't use --enable-preview.

Your code will not compile if you use this method without --enable-preview because the method will be annotated with @jdk.internal.PreviewFeature (instead of @Deprecated).