io.micronaut.annotation.processing.PublicAbstractMethodVisitor Maven / Gradle / Ivy
/*
* Copyright 2017-2018 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.annotation.processing;
import javax.lang.model.element.*;
import javax.lang.model.util.Elements;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Utility visitor that only visits public abstract methods that have not been implemented by the given type.
*
* @param The return type of the visitor's method
* @param The type of the additional parameter to the visitor's methods.
* @author graemerocher
* @see javax.lang.model.util.AbstractTypeVisitor8
* @since 1.0
*/
public abstract class PublicAbstractMethodVisitor extends PublicMethodVisitor {
private final TypeElement classElement;
private final ModelUtils modelUtils;
private final Elements elementUtils;
private Map> declaredMethods = new HashMap<>();
/**
* @param classElement The {@link TypeElement}
* @param modelUtils The {@link ModelUtils}
* @param elementUtils The {@link Elements}
*/
PublicAbstractMethodVisitor(TypeElement classElement, ModelUtils modelUtils, Elements elementUtils) {
super(modelUtils.getTypeUtils());
this.classElement = classElement;
this.modelUtils = modelUtils;
this.elementUtils = elementUtils;
}
@Override
protected boolean isAcceptable(Element element) {
if (element.getKind() == ElementKind.METHOD) {
ExecutableElement executableElement = (ExecutableElement) element;
Set modifiers = executableElement.getModifiers();
String methodName = executableElement.getSimpleName().toString();
boolean acceptable = modelUtils.isAbstract(executableElement) && !modifiers.contains(Modifier.FINAL) && !modifiers.contains(Modifier.STATIC);
boolean isDeclared = executableElement.getEnclosingElement().equals(classElement);
if (acceptable && !isDeclared && declaredMethods.containsKey(methodName)) {
// check method is not overridden already
for (ExecutableElement ex : declaredMethods.get(methodName)) {
if (elementUtils.overrides(ex, executableElement, classElement)) {
return false;
}
}
} else if (!acceptable && !modelUtils.isStatic(executableElement)) {
List declaredMethodList = declaredMethods.computeIfAbsent(methodName, s -> new ArrayList<>());
declaredMethodList.add(executableElement);
}
return acceptable;
} else {
return false;
}
}
}