下面列出了javax.lang.model.element.Element#getKind ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void verifySelfContainedAPI(Element e, TypeElement in) {
switch (e.getKind()) {
case ANNOTATION_TYPE:
case CLASS:
case INTERFACE:
case ENUM:
verifySelfContainedAPI((TypeElement) e);
break;
case CONSTRUCTOR:
case METHOD:
verifySelfContainedAPI((ExecutableElement) e, in);
break;
case FIELD:
verifySelfContainedAPI((VariableElement) e, in);
break;
case PACKAGE:
verifySelfContainedAPI((PackageElement) e);
break;
}
}
@Hint(displayName = "#DN_CanBeFinal", description = "#DESC_CanBeFinal", category="thread", suppressWarnings="FieldMayBeFinal")
@TriggerTreeKind(Kind.VARIABLE)
public static ErrorDescription canBeFinal(HintContext ctx) {
Element ve = ctx.getInfo().getTrees().getElement(ctx.getPath());
if (ve == null || ve.getKind() != ElementKind.FIELD || ve.getModifiers().contains(Modifier.FINAL) || /*TODO: the point of volatile?*/ve.getModifiers().contains(Modifier.VOLATILE)) return null;
//we can't say much currently about non-private fields:
if (!ve.getModifiers().contains(Modifier.PRIVATE)) return null;
FlowResult flow = Flow.assignmentsForUse(ctx);
if (flow == null || ctx.isCanceled()) return null;
if (flow.getFinalCandidates().contains(ve)) {
VariableTree vt = (VariableTree) ctx.getPath().getLeaf();
Fix fix = null;
if (flow.getFieldInitConstructors(ve).size() <= 1) {
fix = FixFactory.addModifiersFix(ctx.getInfo(), new TreePath(ctx.getPath(), vt.getModifiers()), EnumSet.of(Modifier.FINAL), Bundle.FIX_CanBeFinal(ve.getSimpleName().toString()));
}
return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_CanBeFinal(ve.getSimpleName().toString()), fix);
}
return null;
}
@Override
public String toString(List<? extends DocTree> tags, Element element) {
// The content lines below are primarily to help verify the element
// and the values passed to init.
return "<dt>"
+"<span class=\"simpleTagLabel\">Info:</span>\n"
+ "</dt>"
+ "<dd>"
+ "<ul>\n"
+ "<li>Element: " + element.getKind() + " " + element.getSimpleName() + "\n"
+ "<li>Element supertypes: " +
env.getTypeUtils().directSupertypes(element.asType()) + "\n"
+ "<li>Doclet: " + doclet.getClass() + "\n"
+ "</ul>\n"
+ "</dd>";
}
/**
* Checks if an public empty constructor is available
*/
private boolean hasPublicEmptyConstructor(DeclaredType type) {
Element element = type.asElement();
List<? extends Element> containing = element.getEnclosedElements();
for (Element e : containing) {
if (e.getKind() == ElementKind.CONSTRUCTOR) {
ExecutableElement c = (ExecutableElement) e;
if ((c.getParameters() == null || c.getParameters().isEmpty()) && c.getModifiers()
.contains(javax.lang.model.element.Modifier.PUBLIC)) {
return true;
}
}
}
return false;
}
@Override
public CommandFragmentMetaModel visitType(TypeElement type, Void p) {
List<MetaModel<?>> params = null;
for (Element elt : type.getEnclosedElements()) {
if (elt.getKind() == ElementKind.CONSTRUCTOR && elt.getAnnotation(Creator.class) != null) {
params = elt.accept(new ConstructorVisitor(), null);
break;
}
}
if (params != null) {
String pkg = env.getElementUtils().getPackageOf(type).getQualifiedName().toString();
CommandFragmentMetaModel model = new CommandFragmentMetaModel(type, pkg, params);
fragmentsByQualifiedName.put(type.getQualifiedName().toString(), model);
return model;
}
env.getMessager().printMessage(Diagnostic.Kind.ERROR,
String.format("No constructor annotated with @%s found", Creator.class.getSimpleName()),
type);
return null;
}
public boolean isGetterForField(Element elem, String field, TypeKind typeKind){
return elem != null && ExecutableElement.class.isInstance(elem)
&& elem.getKind() == ElementKind.METHOD
&& elem.getSimpleName().toString().toLowerCase().equals("get" + field.toLowerCase())
&& ((ExecutableElement) elem).getReturnType().getKind() == typeKind
&& ((ExecutableElement) elem).getParameters().size() == 0;
}
@Nullable
public String getDescriptor(Element element) {
ElementKind kind = element.getKind();
if (kind.isClass() || kind.isInterface()) {
return null;
}
return getType(element).getDescriptor();
}
private String getName(Element e) {
if (e.getKind().isClass() || e.getKind().isInterface()) {
return processingEnv.getElementUtils().getBinaryName((TypeElement)e).toString();
} else if (e.getKind() == ElementKind.PACKAGE) {
return e.getSimpleName().toString();
} else {
return getName(e.getEnclosingElement()) + '.' + e.getSimpleName();
}
}
private static String findGetterMethod(Element classElement,
VariableElement fieldElement,
AutoBundleField fieldAnnotation) {
final String operation = "get";
final String argKeyName = fieldAnnotation.key().length() > 0
? fieldAnnotation.key() : fieldElement.toString();
for (Element element : classElement.getEnclosedElements()) {
final String methodName = element.getSimpleName().toString();
AutoBundleGetter annotation = element.getAnnotation(AutoBundleGetter.class);
if (annotation != null) {
// annotated getter
if (argKeyName.equals(annotation.key())) {
// check modifier
if (element.getModifiers().contains(Modifier.PRIVATE)) {
throw new ProcessingException("@AutoBundleGetter must not be private");
}
return methodName;
}
} else {
// default getter
if (ElementKind.METHOD == element.getKind() &&
!element.getModifiers().contains(Modifier.PRIVATE) &&
element.getSimpleName().toString().startsWith(operation)) {
if (methodName.equals(
createOperationMethod(operation, argKeyName))) {
int methodModifierLevel = ModifierHelper.getModifierLevel(element);
int fieldModifierLevel = ModifierHelper.getModifierLevel(fieldElement);
if (methodModifierLevel - fieldModifierLevel >= 0) {
return methodName;
}
}
}
}
}
return null;
}
@Override
protected boolean executeRound(Element el, int round) throws Exception {
if (el.getKind() != ElementKind.ENUM) {
return false;
}
ClassTree ct = (ClassTree)path.getLeaf();
for (ListIterator<? extends Tree> it = ct.getMembers().listIterator(ct.getMembers().size()); it.hasPrevious(); ) {
Tree t = it.previous();
if (t.getKind() != Tree.Kind.VARIABLE) {
continue;
}
TreePath p = new TreePath(path, t);
Element e = copy.getTrees().getElement(p);
if (e == null || e.getKind() != ElementKind.ENUM_CONSTANT) {
continue;
}
switch (round) {
case 0:
if (!generateClassBody(p)) {
return false;
}
break;
case 1:
if (!generateImplementation(el, p)) {
return false;
}
break;
default:
throw new IllegalStateException();
}
}
return true;
}
static Element collectClassSegments(Element start, List<String> classSegments) {
Element e = start;
for (; e.getKind() != ElementKind.PACKAGE; e = e.getEnclosingElement()) {
classSegments.add(e.getSimpleName().toString());
}
Collections.reverse(classSegments);
return e;
}
@TriggerPatterns({
@TriggerPattern(value = "new java.lang.StringBuffer($x)", constraints = @ConstraintVariableType(variable = "$x", type = "char")),
@TriggerPattern(value = "new java.lang.StringBuilder($x)", constraints = @ConstraintVariableType(variable = "$x", type = "char"))
})
public static ErrorDescription run(HintContext ctx) {
TreePath p = ctx.getPath();
TypeMirror paramType = ctx.getInfo().getTrees().getTypeMirror(ctx.getVariables().get("$x")); // NOI18N
if (paramType.getKind() != TypeKind.CHAR) {
if (paramType.getKind() != TypeKind.DECLARED) {
return null;
}
Element el = ((DeclaredType)paramType).asElement();
if (el == null || el.getKind() != ElementKind.CLASS) {
return null;
}
if (!((TypeElement)el).getQualifiedName().contentEquals("java.lang.Character")) {
return null;
}
}
TypeMirror tm = ctx.getInfo().getTrees().getTypeMirror(p);
CharSequence tname = ctx.getInfo().getTypeUtilities().getTypeName(tm);
return ErrorDescriptionFactory.forTree(ctx, p, Bundle.TEXT_StringBufferCharConstructor(tname),
new NewAndAppendFix(TreePathHandle.create(p, ctx.getInfo()), tname.toString()).toEditorFix());
}
public void annotateElement(Element element, TypeElement annotation) {
elementsByAnnotation.put(annotation, element);
if (element.getKind() == ElementKind.CLASS) {
addRootElement(element);
} else if (element instanceof ExecutableElement) {
addReturnTypeAsRootElement(element);
}
}
/**
* Detect source type.
*
* @param element the element
* @param adapterClazz the adapter clazz
* @return the string
*/
public static String detectSourceType(Element element, String adapterClazz) {
TypeElement a = BaseProcessor.elementUtils.getTypeElement(adapterClazz);
for (Element i : BaseProcessor.elementUtils.getAllMembers(a)) {
if (i.getKind() == ElementKind.METHOD && "toJava".equals(i.getSimpleName().toString())) {
ExecutableElement method = (ExecutableElement) i;
return TypeUtility.typeName(method.getReturnType()).toString();
}
}
AssertKripton.fail("In '%s', class '%s' can not be used as type adapter", element, adapterClazz);
return null;
}
private static Element getTopLevelClass(Element element) {
Element prev = element;
Element enclosing = element.getEnclosingElement();
while (enclosing != null && enclosing.getKind() != ElementKind.PACKAGE) {
prev = enclosing;
enclosing = enclosing.getEnclosingElement();
}
return prev;
}
private void addParameterInlineHint(Tree tree) {
TreePath pp = getCurrentPath().getParentPath();
Tree leaf = pp.getLeaf();
if (leaf != null &&
(leaf.getKind() == Kind.METHOD_INVOCATION || leaf.getKind() == Kind.NEW_CLASS)) {
int pos = -1;
if (leaf.getKind() == Kind.METHOD_INVOCATION) {
pos = MethodInvocationTree.class.cast(leaf).getArguments().indexOf(tree);
} else if (leaf.getKind() == Kind.NEW_CLASS) {
pos = NewClassTree.class.cast(leaf).getArguments().indexOf(tree);
}
if (pos != (-1)) {
Element invoked = info.getTrees().getElement(pp);
if (invoked != null && (invoked.getKind() == ElementKind.METHOD || invoked.getKind() == ElementKind.CONSTRUCTOR)) {
long start = sourcePositions.getStartPosition(info.getCompilationUnit(), tree);
long end = start + 1;
ExecutableElement invokedMethod = (ExecutableElement) invoked;
pos = Math.min(pos, invokedMethod.getParameters().size() - 1);
if (pos != (-1)) {
boolean shouldBeAdded = true;
if (tree.getKind() == Kind.IDENTIFIER &&
invokedMethod.getParameters().get(pos).getSimpleName().equals(
IdentifierTree.class.cast(tree).getName())) {
shouldBeAdded = false;
}
if (shouldBeAdded) {
preText.put(new int[] {(int) start, (int) end},
invokedMethod.getParameters().get(pos).getSimpleName() + ":");
}
}
}
}
}
}
public static TypeName findPrimaryKeyFieldType(String entityFullName) {
TypeElement element = BaseProcessor.elementUtils.getTypeElement(entityFullName);
List<? extends Element> list = BaseProcessor.elementUtils.getAllMembers(element);
// fill property map from current class
Element idField = null;
String enumValue;
for (Element item : list) {
if (item.getKind() == ElementKind.FIELD) {
enumValue = AnnotationUtility.extractAsEnumerationValue(item, BindSqlColumn.class,
AnnotationAttributeType.COLUMN_TYPE);
if (StringUtils.hasText(enumValue) && (ColumnType.valueOf(enumValue) == ColumnType.PRIMARY_KEY
|| ColumnType.valueOf(enumValue) == ColumnType.PRIMARY_KEY_UNMANGED)) {
return TypeUtility.typeName(item);
} else if (item.getSimpleName().toString().equals("id")) {
idField = item;
}
}
}
if (idField != null) {
return TypeUtility.typeName(idField.asType());
}
// go up in class hierarchy and extract other fields
String parentClassName = element.getSuperclass().toString();
if (parentClassName != null && !Object.class.getCanonicalName().equals(parentClassName)) {
TypeElement parentTypeElement = BaseProcessor.elementUtils.getTypeElement(parentClassName);
if (parentTypeElement != null) {
return findPrimaryKeyFieldType(parentClassName);
}
}
return null;
}
@Nullable
public static SpecMethodModel<EventMethod, Void> getRegisterMethod(
TypeElement typeElement,
List<Class<? extends Annotation>> permittedInterStageInputAnnotations,
Messager messager) {
for (Element enclosedElement : typeElement.getEnclosedElements()) {
if (enclosedElement.getKind() != ElementKind.METHOD) {
continue;
}
final ExecutableElement executableElement = (ExecutableElement) enclosedElement;
final Annotation registerRangesAnnotation =
enclosedElement.getAnnotation(OnRegisterRanges.class);
if (registerRangesAnnotation != null) {
final List<MethodParamModel> methodParams =
getMethodParams(
executableElement,
messager,
getPermittedMethodParamAnnotations(permittedInterStageInputAnnotations),
permittedInterStageInputAnnotations,
ImmutableList.of());
return SpecMethodModel.<EventMethod, Void>builder()
.annotations(ImmutableList.of())
.modifiers(ImmutableList.copyOf(new ArrayList<>(executableElement.getModifiers())))
.name(executableElement.getSimpleName())
.returnTypeSpec(generateTypeSpec(executableElement.getReturnType()))
.typeVariables(ImmutableList.copyOf(getTypeVariables(executableElement)))
.methodParams(ImmutableList.copyOf(methodParams))
.representedObject(executableElement)
.build();
}
}
return null;
}
private static ErrorDescription enumHint(HintContext ctx, String baseName, String targetTypeName, String key, Fix... fixes) {
Element type = ctx.getInfo().getTrees().getElement(ctx.getVariables().get("$param"));
if (type == null || type.getKind() != ElementKind.ENUM) {
return null;
}
Element coll = ctx.getInfo().getTrees().getElement(ctx.getVariables().get("$coll"));
if (coll == null || coll.getKind() != ElementKind.CLASS) {
return null;
}
TypeElement base = ctx.getInfo().getElements().getTypeElement(baseName);
if (base == null) {
return null;
}
Types t = ctx.getInfo().getTypes();
if (!t.isSubtype(t.erasure(coll.asType()), t.erasure(base.asType()))) {
return null;
}
if (targetTypeName != null) {
TypeElement target = ctx.getInfo().getElements().getTypeElement(targetTypeName);
if (target == null) {
return null;
}
if (t.isSubtype(t.erasure(coll.asType()), t.erasure(target.asType()))) {
return null;
}
List<? extends TypeMirror> assignedTo = CreateElementUtilities.resolveType(EnumSet.noneOf(ElementKind.class), ctx.getInfo(), ctx.getPath().getParentPath(), ctx.getPath().getLeaf(), (int) ctx.getInfo().getTrees().getSourcePositions().getEndPosition(ctx.getPath().getCompilationUnit(), ctx.getPath().getLeaf()), new TypeMirror[1], new int[1]);
if (assignedTo != null && assignedTo.size() == 1) {
if (t.isSubtype(t.erasure(assignedTo.get(0)), t.erasure(coll.asType())))
return null;
}
}
String displayName = NbBundle.getMessage(Tiny.class, key);
return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), displayName, fixes);
}
public static boolean isExecutableElement(Element e) {
ElementKind kind = e.getKind();
return kind == ElementKind.CONSTRUCTOR || kind == ElementKind.METHOD;
}