Java clean ups are run on the current document whenever it's saved. They can fix a wide variety of issues, from code style to programming mistakes, and can even modernize the sources based on new Java language features. Here is some information on the supported cleanups and the details of what they do.
Whenever a member (field or method) of a class is accessed from within the class,
prefix the access with this.
This is similar to how Python requires the programmer to access members using self.
For instance:
privateintvalue;
publicintgetValue() {
returnvalue;
}becomes:
privateintvalue;
publicintgetValue() {
returnthis.value;
}Whenever there is a static variable or function, prefix the access with the name of the class that the static variable or function belongs to.
For instance:
importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
out.println("moo");
returnvalue * FACTOR;
}
}becomes:
importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
System.out.println("moo");
returnvalue * MyClass.FACTOR;
}
}When a method of a class that overrides a method from a parent class or provides an implementation for a method from an interface, add the @Override annotation.
For example:
publicclassMyRunnerimplementsRunnable {
publicvoidrun() {
System.out.println("Hello, World!");
}
}becomes:
publicclassMyRunnerimplementsRunnable {
@Overridepublicvoidrun() {
System.out.println("Hello, World!");
}
}When a method is marked @deprecated in the Javadoc, but doesn't have the @Deprecated annotation, add the @Deprecated annotation.
This only works if the compiler has been configured to mark deprecated methods without the deprecated annotation
as an info/warning/error in the JDT settings.
For example:
/** * Not used anymore, please stop using. * * @deprecated */publicbooleanisAGoat() {
returnfalse;
}becomes:
/** * Not used anymore, please stop using. * * @deprecated */@DeprecatedpublicbooleanisAGoat() {
returnfalse;
}Appropriate String concatenations will be converted into Java Text Blocks. Appropriate String concatenations must have at least 3 non-empty substrings with one per line and the Java level must be 15 or higher. Line comments for all substrings but the last line will be lost after conversion. Spaces at the end of substrings preceding the newline will result in \s being substituted while substrings that do not end with newlines will have a \ added at the end of the line to preserve concatenation.
For example:
Stringx = "" +
"public class A {\n" +
" public void m() {\n" +
" System.out.println(\"abc\");\n" +
" }\n" +
"}";becomes:
Stringx = """ public class A { public void m() { System.out.println("abc"); } }""";Inverts calls to Object.equals(Object) and String.equalsIgnoreCase(String) to avoid useless null pointer exception.
The caller must be nullable and the parameter must not be nullable.
By avoiding null pointer exceptions, the behavior may change.
For example:
Stringmessage = getMessage();
booleanresult1 = message.equals("text");
booleanresult2 = message.equalsIgnoreCase("text");becomes:
Stringmessage = getMessage();
booleanresult1 = "text".equals(message);
booleanresult2 = "text".equalsIgnoreCase(message);Use the final modifier for variable declarations wherever it is possible.
For example:
privateinti= 0;
publicvoidfoo(intj) {
intk, h;
h= 0;
}becomes:
privatefinalinti= 0;
publicvoidfoo(finalintj) {
finalintk;
inth;
h= 0;
}Use pattern matching for the instanceof operator wherever possible. It is only applicable for Java level 15 or higher.
For example:
if (objectinstanceofInteger) {
Integeri = (Integer) object;
returni.intValue();
}becomes:
if (objectinstanceofIntegeri) {
returni.intValue();
}Convert anonymous class declarations for functional interfaces to lambda expressions wherever possible. It is only applicable for Java level 8 or above.
For example:
IntConsumerc = newIntConsumer() {
@Overridepublicvoidaccept(intvalue) {
System.out.println(i);
}
};becomes:
IntConsumerc = i -> {
System.out.println(i);
};Convert switch statements to switch expressions wherever possible. It is only applicable for Java level 14 or above.
Note : Switch statements that use control statements such as nested switch statements, if/else blocks, for/while loops are not considered as is the case for return/continue statements. All cases of the switch statement must either have a last assignment statement that sets the same variable/field as other cases, or else has a throw statement. Fall-through is allowed between cases but only if there are no other statements in between. The switch statement must have a default case unless the switch expression is an enum type and all possible enum values are represented in the cases.
For example:
inti;
switch(j) {
case1:
i = 3;
break;
case2:
i = 4;
break;
default:
i = 0;
break;
}becomes:
inti = switch(j) {
case1 -> 3;
case2 -> 4;
default -> 0;
};Simplifies the finally block to use the try-with-resource statement.
For example:
finalFileInputStreaminputStream = newFileInputStream("out.txt");
try {
System.out.println(inputStream.read());
} finally {
inputStream.close();
}becomes:
finalFileInputStreaminputStream = newFileInputStream("out.txt");
try (inputStream) {
System.out.println(inputStream.read());
}Cleans up lambda expression wherever possible in the following ways:
Removes unnecessary parentheses.
For example:
(someString) -> someString.trim().toLowerCase();
becomes:
someString -> someString.trim().toLowerCase();
Converts lambda expression blocks to a single statement when possible.
For example:
someString -> {returnsomeString.trim().toLowerCase();};
becomes:
someString -> someString.trim().toLowerCase();
Converts lambda expression to method reference.
For example:
() -> newArrayList<>();
becomes:
ArrayList::new;
Performs the "Organize Imports" operation.
Note : Since clean ups are meant to be applied without user feedback (eg. prompts about ambiguous types), this may leave some types unresolved. To properly resolve these ambiguous types, one can do so manually (code actions, source actions), or by calling "Organize Imports" through the command palette / key binding (shift + alt + o).
For example:
packagetest1;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}becomes:
packagetest1;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.URI;
importjava.nio.file.Path;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importjava.util.Set;
importjava.util.StringTokenizer;
importjava.util.jar.JarFile;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}Rename unused loop variables, try-with-resource variables, catch parameters, lambda parameters, pattern variables to _.
For example:
Jj = (a, b) -> System.out.println(a);
switch (r) {
caseR(_, longl) -> {}
caseRr2 -> {}
}becomes:
Jj = (a, _) -> System.out.println(a);
switch (r) {
caseR(_, _) -> {}
caseR_ -> {}
}Convert if/else chains to pattern matching switch statements.
For example:
inti, j;
doubled;
booleanb;
if (xinstanceofIntegerxint) {
i = xint.intValue();
} elseif (xinstanceofDoublexdouble) {
d = xdouble.doubleValue();
} elseif (xinstanceofBooleanxboolean) {
b = xboolean.booleanValue();
} else {
i = 0;
d = 0.0D;
b = false;
}becomes:
inti, j;
doubled;
booleanb;
switch (x) {
caseIntegerxint -> i = xint.intValue();
caseDoublexdouble -> d = xdouble.doubleValue();
caseBooleanxboolean -> b = xboolean.booleanValue();
casenull, default -> {
i = 0;
d = 0.0D;
b = false;
}
}Remove redundant comparison statement.
For example:
if (i != 123) {
returni;
} else {
return123;
}becomes:
returni;Remove redundant end of block with jump statement.
For example:
if (0 < i) {
System.out.println("Doing something");
returni + 10;
}
returni + 10;becomes:
if (0 < i) {
System.out.println("Doing something");
}
returni + 10;Remove redundant if condition.
For example:
if (isValid) {
return0;
} elseif (!isValid) {
return -1;
}becomes:
if (isValid) {
return0;
} else {
return -1;
}Remove redundant modifiers.
For example:
publicabstractinterfaceIFoo {
publicstaticfinalintMAGIC_NUMBER = 646;
publicabstractintfoo ();
publicintbar (intbazz);
}becomes:
publicinterfaceIFoo {
intMAGIC_NUMBER = 646;
intfoo ();
intbar (intbazz);
}Remove redundant super() class in constructor.
For example:
MyClass() {
super();
}becomes:
MyClass() {
}