@ Override public void endVisit ( MethodDeclaration node ) { ExecutableElement element = node . getExecutableElement ( ) ; if ( ! ElementUtil . getName ( element ) . equals ( "compareTo" ) || node . getBody ( ) == null ) { return ; } DeclaredType comparableType = typeUtil . findSupertype ( ElementUtil . getDeclaringClass ( element ) . asType ( ) , "java.lang.Comparable" ) ; if ( comparableType == null ) { return ; } List < ? extends TypeMirror > typeArguments = comparableType . getTypeArguments ( ) ; List < ? extends VariableElement > parameters = element . getParameters ( ) ; if ( typeArguments . size ( ) != 1 || parameters . size ( ) != 1 || ! typeArguments . get ( 0 ) . equals ( parameters . get ( 0 ) . asType ( ) ) ) { return ; } VariableElement param = node . getParameter ( 0 ) . getVariableElement ( ) ; FunctionInvocation castCheck = createCastCheck ( typeArguments . get ( 0 ) , new SimpleName ( param ) ) ; if ( castCheck != null ) { node . getBody ( ) . addStatement ( 0 , new ExpressionStatement ( castCheck ) ) ; } }
Adds a cast check to compareTo methods . This helps Comparable types behave well in sorted collections which rely on Java s runtime type checking .