|
| 1 | +package org.openrewrite.java.migrate; |
| 2 | + |
| 3 | +import org.openrewrite.ExecutionContext; |
| 4 | +import org.openrewrite.Recipe; |
| 5 | +import org.openrewrite.TreeVisitor; |
| 6 | +import org.openrewrite.java.JavaVisitor; |
| 7 | +import org.openrewrite.java.tree.J; |
| 8 | +import org.openrewrite.java.tree.JavaType; |
| 9 | + |
| 10 | +import java.util.Collections; |
| 11 | +import java.util.List; |
| 12 | + |
| 13 | +public class HandleTypeNotPresentExceptionInsteadOfArrayStoreException extends Recipe { |
| 14 | + @Override |
| 15 | + public String getDisplayName() { |
| 16 | + return "Handle TypeNotPresentException instead of ArrayStoreException"; |
| 17 | + } |
| 18 | + |
| 19 | + @Override |
| 20 | + public String getDescription() { |
| 21 | + return "This recipe replaces catch blocks for ArrayStoreException around getAnnotation() with TypeNotPresentException or both exceptions, to ensure compatibility with Java 11+."; |
| 22 | + } |
| 23 | + |
| 24 | + @Override |
| 25 | + public TreeVisitor<?, ExecutionContext> getVisitor() { |
| 26 | + return new JavaVisitor<ExecutionContext>() { |
| 27 | + @Override |
| 28 | + public J visitTry(J.Try tryStmt, ExecutionContext ctx ) { |
| 29 | + if(containsGetAnnotation(tryStmt.getBody())) |
| 30 | + { |
| 31 | + for (J.Try.Catch catchClause : tryStmt.getCatches()) { |
| 32 | + if(catchClause.getParameter().getType() != null && "java.lang.ArrayStoreException".equals(catchClause.getParameter().getType().toString())) { |
| 33 | + JavaType.Class typeNotPresentExceptionType = new JavaType.Class(null,0,"java.lang.TypeNotPresentException", null, null,null, null,null,null,null,null); |
| 34 | + J.Try.Catch updatedCatch = catchClause.withParameter(catchClause.getParameter().withType(typeNotPresentExceptionType)); |
| 35 | +// String multiCatchType = "java.lang.ArrayStoreException | java.lang.TypeNotPresentException"; |
| 36 | +// updatedCatch = updatedCatch.withParameter(catchClause.getParameter().withType(JavaType.Class.build(multicatchType))); |
| 37 | + tryStmt = tryStmt.withCatches((List<J.Try.Catch>) Collections.singleton(updatedCatch)); |
| 38 | + } |
| 39 | + } |
| 40 | + } |
| 41 | + return super.visitTry(tryStmt,ctx); |
| 42 | + } |
| 43 | + |
| 44 | + private boolean containsGetAnnotation(J.Block body) { |
| 45 | + if(body == null) return false; |
| 46 | + for( J node : body.getStatements()) { |
| 47 | + if (node instanceof J.MethodInvocation) { |
| 48 | + J.MethodInvocation methodInvocation = (J.MethodInvocation) node; |
| 49 | + if ("getAnnotation".equals(methodInvocation.getSimpleName())) { |
| 50 | + return true; |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + return false; |
| 55 | +} |
| 56 | + }; |
| 57 | + } |
| 58 | +} |
| 59 | + |
0 commit comments