@@ -48,40 +48,41 @@ public String getDescription() {
4848
4949 @ Override
5050 public TreeVisitor <?, ExecutionContext > getVisitor () {
51- return Preconditions .check (Preconditions .and (new UsesJavaVersion <>(10 ), new UsesMethod <>(NEW_HASH_MAP )), new JavaVisitor <ExecutionContext >() {
52- @ Override
53- public J visitNewClass (J .NewClass newClass , ExecutionContext ctx ) {
54- J .NewClass n = (J .NewClass ) super .visitNewClass (newClass , ctx );
55- J .Block body = n .getBody ();
56- if (NEW_HASH_MAP .matches (n ) && body != null ) {
57- if (body .getStatements ().size () == 1 ) {
58- Statement statement = body .getStatements ().get (0 );
59- if (statement instanceof J .Block ) {
60- List <Expression > args = new ArrayList <>();
61- StringJoiner mapOf = new StringJoiner (", " , "Map.of(" , ")" );
62- for (Statement stat : ((J .Block ) statement ).getStatements ()) {
63- if (stat instanceof J .MethodInvocation && MAP_PUT .matches ((Expression ) stat )) {
64- J .MethodInvocation put = (J .MethodInvocation ) stat ;
65- args .addAll (put .getArguments ());
66- mapOf .add ("#{}" );
67- mapOf .add ("#{}" );
68- } else {
69- return n ;
70- }
71- }
51+ return Preconditions .check (Preconditions .and (new UsesJavaVersion <>(10 ),
52+ new UsesMethod <>(NEW_HASH_MAP )), new UseMapOfVisitor ());
53+ }
7254
73- maybeRemoveImport ("java.util.HashMap" );
74- maybeAddImport ("java.util.Map" );
75- return JavaTemplate .builder (mapOf .toString ())
76- .contextSensitive ()
77- .imports ("java.util.Map" )
78- .build ()
79- .apply (updateCursor (n ), n .getCoordinates ().replace (), args .toArray ());
55+ private static class UseMapOfVisitor extends JavaVisitor <ExecutionContext > {
56+ @ Override
57+ public J visitNewClass (J .NewClass newClass , ExecutionContext ctx ) {
58+ J .NewClass n = (J .NewClass ) super .visitNewClass (newClass , ctx );
59+ J .Block body = n .getBody ();
60+ if (NEW_HASH_MAP .matches (n ) && body != null && body .getStatements ().size () == 1 ) {
61+ Statement statement = body .getStatements ().get (0 );
62+ if (statement instanceof J .Block ) {
63+ List <Expression > args = new ArrayList <>();
64+ StringJoiner mapOf = new StringJoiner (", " , "Map.of(" , ")" );
65+ for (Statement stat : ((J .Block ) statement ).getStatements ()) {
66+ if (!(stat instanceof J .MethodInvocation ) || !MAP_PUT .matches ((Expression ) stat )) {
67+ return n ;
8068 }
69+ J .MethodInvocation put = (J .MethodInvocation ) stat ;
70+ args .addAll (put .getArguments ());
71+ mapOf .add ("#{any()}" );
72+ mapOf .add ("#{any()}" );
8173 }
74+
75+ maybeRemoveImport ("java.util.HashMap" );
76+ maybeAddImport ("java.util.Map" );
77+ return JavaTemplate .builder (mapOf .toString ())
78+ .contextSensitive ()
79+ .imports ("java.util.Map" )
80+ .build ()
81+ .apply (updateCursor (n ), n .getCoordinates ().replace (), args .toArray ());
8282 }
83- return n ;
8483 }
85- });
84+
85+ return n ;
86+ }
8687 }
8788}
0 commit comments