下面列出了javax.lang.model.element.TypeElement#getKind ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected ErrorDescription[] apply(TypeElement subject, ProblemContext ctx) {
AnnotationMirror annEntity = Utilities.findAnnotation(subject, ANNOTATION_WEBSERVICE);
AnnotationTree annotationTree = (AnnotationTree) ctx.getCompilationInfo().
getTrees().getTree(subject, annEntity);
if (subject.getKind() == ElementKind.CLASS) {
AnnotationValue seiValue = Utilities.getAnnotationAttrValue(annEntity,
ANNOTATION_ATTRIBUTE_SEI);
if (seiValue != null && Utilities.getAnnotationAttrValue(annEntity,
ANNOTATION_ATTRIBUTE_NAME) != null) {
//check for name attribute
String label = NbBundle.getMessage(InvalidNameAttribute.class,
"MSG_NameAttributeNotAllowed");
Tree problemTree = Utilities.getAnnotationArgumentTree
(annotationTree, ANNOTATION_ATTRIBUTE_NAME);
Fix removeFix = new RemoveAnnotationArgument(ctx.getFileObject(),
subject, annEntity, ANNOTATION_ATTRIBUTE_NAME);
ctx.setElementToAnnotate(problemTree);
ErrorDescription problem = createProblem(subject, ctx, label, removeFix);
ctx.setElementToAnnotate(null);
return new ErrorDescription[]{problem};
}
}
return null;
}
@Override
protected void lateValidateSuper(TypeElement t) {
super.lateValidateSuper(t);
if (t.getKind() == ElementKind.CLASS) {
String superclassString = SourceExtraction.getSuperclassString(t);
String rawSuperclass = SourceTypes.extract(superclassString).getKey();
// We need to extend the base class
if (!rawSuperclass.equals(typeAbstract().toString())) {
protoclass()
.report()
.withElement(t)
.error("%s needs to extend the base class",
t.getSimpleName());
}
}
}
@Override public ErrorDescription[] apply(TypeElement subject, ProblemContext ctx){
if(subject.getKind() == ElementKind.INTERFACE) {
AnnotationMirror annEntity = Utilities.findAnnotation(subject,ANNOTATION_WEBSERVICE);
AnnotationTree annotationTree = (AnnotationTree) ctx.getCompilationInfo().
getTrees().getTree(subject, annEntity);
//endpointInterface not allowed
if(Utilities.getAnnotationAttrValue(annEntity, ANNOTATION_ATTRIBUTE_SEI)!=null) {
String label = NbBundle.getMessage(InterfaceEndpointInterface.class, "MSG_IF_SEINotAllowed");
Fix fix = new RemoveAnnotationArgument(ctx.getFileObject(),
subject, annEntity, ANNOTATION_ATTRIBUTE_SEI);
Tree problemTree = Utilities.getAnnotationArgumentTree(annotationTree, ANNOTATION_ATTRIBUTE_SEI);
ctx.setElementToAnnotate(problemTree);
ErrorDescription problem = createProblem(subject, ctx, label, fix);
ctx.setElementToAnnotate(null);
return new ErrorDescription[]{problem};
}
}
return null;
}
private CompletionItem createItem(ElementHandle<TypeElement> handle, int priority) {
TypeElement el = handle.resolve(ctx.getCompilationInfo());
if (el == null) {
// element does not exist etc
return null;
}
if (el.getKind() != ElementKind.CLASS && el.getKind() != ElementKind.ENUM) {
// do not honour interfaces
return null;
}
if (!el.getModifiers().contains(Modifier.PUBLIC)) {
return null;
}
CompletionItem item = null;
Collection<? extends ClassItemFactory> converters = MimeLookup.getLookup(JavaFXEditorUtils.FXML_MIME_TYPE).lookupAll(ClassItemFactory.class);
for (ClassItemFactory converter : converters) {
item = converter.convert(el, ctx, priority);
if (item != null) {
break;
}
}
return item;
}
public boolean isTableElementValid(TableElement tableElement) {
final TypeElement rawElement = tableElement.getTableElement();
if (rawElement.getKind() != ElementKind.CLASS) {
environment.error(rawElement, ERR_TABLE_MISPLACEMENT);
return false;
}
if (rawElement.getModifiers().contains(ABSTRACT) && !environment.hasAutoValueLib()) {
environment.error(rawElement, "%s is an abstract class, but project is missing configured AutoValue library [%s] " +
"and abstract classes by themselves are not supported as table objects",
rawElement.getSimpleName().toString(),
environment.getAutoValueAnnotationQualifiedName());
return false;
}
if (tableElement.getAllColumns().isEmpty()) {
environment.error(rawElement, ERR_MISSING_COLUMNS);
return false;
}
if (tableElement.isImmutable()) {
return isImmutableTableElementValid(tableElement, rawElement);
}
return isRegularTableElementValid(rawElement);
}
public static boolean isInjectionTarget(CompilationController controller, TypeElement typeElement) {
FileObject fo = controller.getFileObject();
Project project = FileOwnerQuery.getOwner(fo);
if (ElementKind.INTERFACE != typeElement.getKind()) {
List<? extends AnnotationMirror> annotations = typeElement.getAnnotationMirrors();
boolean found = false;
for (AnnotationMirror m : annotations) {
Name qualifiedName = ((TypeElement) m.getAnnotationType().asElement()).getQualifiedName();
if (qualifiedName.contentEquals("javax.jws.WebService")) {
//NOI18N
found = true;
break;
}
if (qualifiedName.contentEquals("javax.jws.WebServiceProvider")) {
//NOI18N
found = true;
break;
}
}
if (found) {
return true;
}
}
return false;
}
protected ErrorDescription[] apply(TypeElement subject, ProblemContext ctx) {
ArrayList<ErrorDescription> errors = new ArrayList<ErrorDescription>();
AnnotationMirror annEntity = Utilities.findAnnotation(subject, ANNOTATION_WEBSERVICE);
if (subject.getKind() == ElementKind.CLASS && Utilities.getAnnotationAttrValue
(annEntity, ANNOTATION_ATTRIBUTE_SEI) != null) {
for (String aName : new String[]{
ANNOTATION_WEBMETHOD,
ANNOTATION_WEBPARAM,
ANNOTATION_WEBRESULT,
ANNOTATION_ONEWAY,
ANNOTATION_SOAPMESSAGEHANDLERS,
ANNOTATION_INITPARAM,
ANNOTATION_SOAPBINDING,
ANNOTATION_SOAPMESSAGEHANDLER}) {
AnnotationMirror wrongAnnon = Utilities.findAnnotation(subject, aName);
if (wrongAnnon != null) {
String label = NbBundle.getMessage(InvalidJSRAnnotations.class, "MSG_Invalid_JSR181Annotation");
Tree problemTree = ctx.getCompilationInfo().getTrees().getTree(subject, wrongAnnon);
Fix removeHC = new RemoveAnnotation(ctx.getFileObject(), subject, wrongAnnon);
ctx.setElementToAnnotate(problemTree);
errors.add(createProblem(subject, ctx, label, removeHC));
ctx.setElementToAnnotate(null);
}
}
}
return errors.isEmpty() ? null : errors.toArray(new ErrorDescription[errors.size()]);
}
public boolean isFunctionalInterface(TypeElement type) {
if (type != null && type.getKind() == ElementKind.INTERFACE) {
ReferenceBinding binding = (ReferenceBinding)((TypeElementImpl) type)._binding;
if (binding instanceof SourceTypeBinding) {
return binding.isFunctionalInterface(((SourceTypeBinding) binding).scope);
}
}
return false;
}
Void printType(TypeElement e, DeclaredType dt, Boolean highlightName) {
modifier(e.getModifiers());
switch (e.getKind()) {
case CLASS:
result.append("class ");
break;
case INTERFACE:
result.append("interface ");
break;
case ENUM:
result.append("enum ");
break;
case ANNOTATION_TYPE:
result.append("@interface ");
break;
}
Element enclosing = e.getEnclosingElement();
if (enclosing == SourceUtils.getEnclosingTypeElement(e)) {
result.append(((TypeElement) enclosing).getQualifiedName());
result.append('.');
boldStartCheck(highlightName);
result.append(e.getSimpleName());
boldStopCheck(highlightName);
} else {
result.append(e.getQualifiedName());
}
if (dt != null) {
dumpRealTypeArguments(dt.getTypeArguments());
}
return null;
}
@Override
public void run(CompilationController controller) throws Exception {
controller.toPhase(Phase.RESOLVED);
fileObject = controller.getFileObject();
TypeElement typeElement = null;
List<? extends TypeElement> topLevelElements = controller.getTopLevelElements();
for (Iterator<? extends TypeElement> it = topLevelElements.iterator(); it.hasNext();) {
typeElement = it.next();
if (typeElement.getKind() == ElementKind.CLASS) {
className = typeElement.getSimpleName().toString();
break;
}
}
Elements elements = controller.getElements();
TypeElement testcase = elements.getTypeElement(TESTCASE);
boolean junit3 = (testcase != null && typeElement != null) ? controller.getTypes().isSubtype(typeElement.asType(), testcase.asType()) : false;
TreePath tp = controller.getTreeUtilities().pathFor(caretPosition);
while (tp != null && tp.getLeaf().getKind() != Kind.METHOD) {
tp = tp.getParentPath();
}
if (tp != null) {
Element element = controller.getTrees().getElement(tp);
if (element != null) {
String mn = element.getSimpleName().toString();
if (junit3) {
methodName = mn.startsWith("test") ? mn : null; //NOI18N
} else {
List<? extends AnnotationMirror> allAnnotationMirrors = elements.getAllAnnotationMirrors(element);
if (isJunit4Test(allAnnotationMirrors) || isJunit5Testable(allAnnotationMirrors)) {
methodName = mn;
}
}
}
}
}
private static boolean isEnable(FileObject srcFile, TypeElement typeElement) {
Project project = FileOwnerQuery.getOwner(srcFile);
if (project == null) {
return false;
}
J2eeModuleProvider j2eeModuleProvider = project.getLookup ().lookup (J2eeModuleProvider.class);
if (j2eeModuleProvider != null) {
if (project.getLookup().lookup(EnterpriseReferenceContainer.class) == null) {
return false;
}
String serverInstanceId = j2eeModuleProvider.getServerInstanceID();
if (serverInstanceId == null) {
return true;
}
J2eePlatform platform = null;
try {
platform = Deployment.getDefault().getServerInstance(serverInstanceId).getJ2eePlatform();
} catch (InstanceRemovedException ex) {
Logger.getLogger(CallEjbCodeGenerator.class.getName()).log(Level.FINE, null, ex);
}
if (platform == null) {
return true;
}
if (!EjbSupport.getInstance(platform).isEjb31LiteSupported(platform)
&& !platform.getSupportedTypes().contains(J2eeModule.Type.EJB)) {
return false;
}
} else {
return false;
}
return ElementKind.INTERFACE != typeElement.getKind();
}
/**
* Checks whether the given type object represents type
* {@code java.lang.Object}.
*
* @param type type to be checked
* @return {@code true} if the passed type object represents type
* {@code java.lang.Object}, {@code false} otherwise
*/
private static boolean isRootObjectType(DeclaredType type) {
if (type.getKind() != TypeKind.DECLARED) {
return false;
}
TypeElement elem = (TypeElement) type.asElement();
return (elem.getKind() == ElementKind.CLASS)
&& (elem.getSuperclass().getKind() == TypeKind.NONE);
}
/**
* Finds a main top-level class or a nested class element
* for {@code sourceDataObject} which should be initialized.
*/
private TypeElement getClass(WorkingCopy workingCopy)
throws IOException {
workingCopy.toPhase(Phase.ELEMENTS_RESOLVED);
final String preferredName = sourceDataObject.getName();
TypeElement firstPublicNestedClass = null;
List<? extends TypeElement> topClasses = workingCopy.getTopLevelElements();
for (TypeElement topElement : topClasses) {
ElementKind elementKind = topElement.getKind();
if (!elementKind.isClass()) {
continue;
}
if (topElement.getSimpleName().contentEquals(preferredName)) {
return topElement;
}
if ((firstPublicNestedClass == null)
&& topElement.getModifiers().contains(Modifier.PUBLIC)) {
firstPublicNestedClass = topElement;
}
}
return firstPublicNestedClass;
}
private void processType(TypeElement type) {
RetroWeibo autoValue = type.getAnnotation(RetroWeibo.class);
if (autoValue == null) {
// This shouldn't happen unless the compilation environment is buggy,
// but it has happened in the past and can crash the compiler.
errorReporter.abortWithError("annotation processor for @RetroWeibo was invoked with a type"
+ " that does not have that annotation; this is probably a compiler bug", type);
}
if (type.getKind() != ElementKind.CLASS) {
errorReporter.abortWithError(
"@" + RetroWeibo.class.getName() + " only applies to classes", type);
}
if (ancestorIsRetroWeibo(type)) {
errorReporter.abortWithError("One @RetroWeibo class may not extend another", type);
}
if (implementsAnnotation(type)) {
errorReporter.abortWithError("@RetroWeibo may not be used to implement an annotation"
+ " interface; try using @AutoAnnotation instead", type);
}
RetroWeiboTemplateVars vars = new RetroWeiboTemplateVars();
vars.pkg = TypeSimplifier.packageNameOf(type);
vars.origClass = TypeSimplifier.classNameOf(type);
vars.simpleClassName = TypeSimplifier.simpleNameOf(vars.origClass);
vars.subclass = TypeSimplifier.simpleNameOf(generatedSubclassName(type));
defineVarsForType(type, vars);
GwtCompatibility gwtCompatibility = new GwtCompatibility(type);
vars.gwtCompatibleAnnotation = gwtCompatibility.gwtCompatibleAnnotationString();
String text = vars.toText();
text = Reformatter.fixup(text);
writeSourceFile(generatedSubclassName(type), text, type);
GwtSerialization gwtSerialization = new GwtSerialization(gwtCompatibility, processingEnv, type);
gwtSerialization.maybeWriteGwtSerializer(vars);
}
@Override
public void process( TypeElement typeElement, TypeProcessor typeProcessor, IssueReporter<JavaFileObject> issueReporter )
{
if( typeElement.getKind() == ElementKind.CLASS || typeElement.getKind() == ElementKind.ENUM || typeElement.getKind() == ElementKind.INTERFACE )
{
TreeTranslator visitor = new ExtensionTransformer( this, typeProcessor );
typeProcessor.getTree().accept( visitor );
}
}
/** Basic sanity-checking to ensure we can fulfil the @FreeBuilder contract for this type. */
private void verifyType(TypeElement type, PackageElement pkg) throws CannotGenerateCodeException {
if (pkg.isUnnamed()) {
messager.printMessage(ERROR, "FreeBuilder does not support types in unnamed packages", type);
throw new CannotGenerateCodeException();
}
switch (type.getNestingKind()) {
case TOP_LEVEL:
break;
case MEMBER:
if (!type.getModifiers().contains(Modifier.STATIC)) {
messager.printMessage(
ERROR,
"Inner classes cannot be FreeBuilder types (did you forget the static keyword?)",
type);
throw new CannotGenerateCodeException();
}
if (type.getModifiers().contains(Modifier.PRIVATE)) {
messager.printMessage(ERROR, "FreeBuilder types cannot be private", type);
throw new CannotGenerateCodeException();
}
for (Element e = type.getEnclosingElement(); e != null; e = e.getEnclosingElement()) {
if (e.getModifiers().contains(Modifier.PRIVATE)) {
messager.printMessage(
ERROR,
"FreeBuilder types cannot be private, but enclosing type "
+ e.getSimpleName() + " is inaccessible",
type);
throw new CannotGenerateCodeException();
}
}
break;
default:
messager.printMessage(
ERROR, "Only top-level or static nested types can be FreeBuilder types", type);
throw new CannotGenerateCodeException();
}
switch (type.getKind()) {
case ANNOTATION_TYPE:
messager.printMessage(ERROR, "FreeBuilder does not support annotation types", type);
throw new CannotGenerateCodeException();
case CLASS:
verifyTypeIsConstructible(type);
break;
case ENUM:
messager.printMessage(ERROR, "FreeBuilder does not support enum types", type);
throw new CannotGenerateCodeException();
case INTERFACE:
// Nothing extra needs to be checked on an interface
break;
default:
throw new AssertionError("Unexpected element kind " + type.getKind());
}
}
/**
* Gets the class access flags (see JVMS8 4.1) for the given type element, augmented by the
* special ASM pseudo-access flag for @Deprecated types.
*/
public int getAccessFlags(TypeElement typeElement) {
ElementKind kind;
try {
kind = typeElement.getKind();
} catch (CannotInferException e) {
Preconditions.checkState(typeElement.getNestingKind().isNested());
// We cannot know the access flags of an inferred type element. However, the only
// flag that matters in the InnerClasses table is ACC_STATIC. When reading the
// InnerClasses table, the compiler may create ClassSymbols for types it hasn't
// seen before, and the absence of ACC_STATIC will cause it to mark those
// ClassSymbols as inner classes, and it will not correct that when later loading
// the class from its definitive class file. However, it is safe to mark
// everything with ACC_STATIC, because the compiler *will* properly update
// non-static classes when loading their definitive class files.
// (http://hg.openjdk.java.net/jdk8u/jdk8u/langtools/file/9986bf97a48d/src/share/classes/com/sun/tools/javac/jvm/ClassReader.java#l2272)
return Opcodes.ACC_STATIC;
}
int result = getCommonAccessFlags(typeElement);
switch (kind) {
case ANNOTATION_TYPE:
// No ACC_SUPER here per JVMS 4.1
result = result | Opcodes.ACC_ANNOTATION;
result = result | Opcodes.ACC_INTERFACE;
result = result | Opcodes.ACC_ABSTRACT;
break;
case ENUM:
result = result | Opcodes.ACC_SUPER; // JVMS 4.1
result = result | Opcodes.ACC_ENUM;
if (isAbstractEnum(typeElement)) {
result = result & ~Opcodes.ACC_FINAL | Opcodes.ACC_ABSTRACT;
}
break;
case INTERFACE:
// No ACC_SUPER here per JVMS 4.1
result = result | Opcodes.ACC_ABSTRACT;
result = result | Opcodes.ACC_INTERFACE;
break;
// $CASES-OMITTED$
default:
result = result | Opcodes.ACC_SUPER; // JVMS 4.1
break;
}
return result;
}
Encoding(TypeElement type) {
this.typeEncoding = type;
if (type.getKind() != ElementKind.CLASS || type.getNestingKind() != NestingKind.TOP_LEVEL) {
reporter.withElement(type).error("Encoding type '%s' should be top-level class", type.getSimpleName());
}
this.$$package = processing().getElementUtils().getPackageOf(type).getQualifiedName().toString();
this.name = type.getSimpleName().toString();
CharSequence source = SourceExtraction.extract(processing(), type);
if (source.length() == 0) {
reporter.withElement(type)
.error("No source code can be extracted for @Encoding class. Unsupported compilation mode");
}
this.imports = SourceExtraction.importsFrom(source);
this.sourceMapper = new SourceMapper(source);
this.typesReader = new TypeExtractor(types, type);
this.encodingSelfType = typesReader.get(type.asType());
addTypeParameters(type);
for (Element e : type.getEnclosedElements()) {
processMember(e);
}
if (postValidate()) {
provideSyntheticElements();
}
this.allElements = Iterables.concat(
Arrays.asList(
Iterables.filter(
Arrays.asList(
impl,
from,
toString,
hashCode,
equals,
build,
isInit),
Predicates.notNull()),
fields,
expose,
copy,
helpers,
builderFields,
builderHelpers,
builderInits));
this.linkage = new Linkage();
this.generatedImports = generatedImports();
}
static boolean isTestable(TypeElement typeDeclElement) {
ElementKind elemKind = typeDeclElement.getKind();
return (elemKind != ElementKind.ANNOTATION_TYPE)
&& (elemKind.isClass()|| elemKind.isInterface());
}
@Override
public Class<?> visitDeclared(DeclaredType t, Void p) {
TypeElement typeElement = ctx.getMoreTypes().toTypeElement(t);
if (typeElement == null) {
return null;
}
if (typeElement.getKind() == ElementKind.ENUM) {
return EnumWrapper.class;
}
String name = typeElement.getQualifiedName().toString();
if (String.class.getName().equals(name)) {
return StringWrapper.class;
}
if (Boolean.class.getName().equals(name)) {
return BooleanWrapper.class;
}
if (Byte.class.getName().equals(name)) {
return ByteWrapper.class;
}
if (Short.class.getName().equals(name)) {
return ShortWrapper.class;
}
if (Integer.class.getName().equals(name)) {
return IntegerWrapper.class;
}
if (Long.class.getName().equals(name)) {
return LongWrapper.class;
}
if (Float.class.getName().equals(name)) {
return FloatWrapper.class;
}
if (Double.class.getName().equals(name)) {
return DoubleWrapper.class;
}
if (Object.class.getName().equals(name)) {
return ObjectWrapper.class;
}
if (ctx.getMoreTypes().isAssignableWithErasure(t, BigDecimal.class)) {
return BigDecimalWrapper.class;
}
if (ctx.getMoreTypes().isAssignableWithErasure(t, BigInteger.class)) {
return BigIntegerWrapper.class;
}
if (ctx.getMoreTypes().isAssignableWithErasure(t, Time.class)) {
return TimeWrapper.class;
}
if (ctx.getMoreTypes().isAssignableWithErasure(t, Timestamp.class)) {
return TimestampWrapper.class;
}
if (ctx.getMoreTypes().isAssignableWithErasure(t, Date.class)) {
return DateWrapper.class;
}
if (ctx.getMoreTypes().isAssignableWithErasure(t, java.util.Date.class)) {
return UtilDateWrapper.class;
}
if (ctx.getMoreTypes().isAssignableWithErasure(t, LocalTime.class)) {
return LocalTimeWrapper.class;
}
if (ctx.getMoreTypes().isAssignableWithErasure(t, LocalDateTime.class)) {
return LocalDateTimeWrapper.class;
}
if (ctx.getMoreTypes().isAssignableWithErasure(t, LocalDate.class)) {
return LocalDateWrapper.class;
}
if (ctx.getMoreTypes().isAssignableWithErasure(t, Array.class)) {
return ArrayWrapper.class;
}
if (ctx.getMoreTypes().isAssignableWithErasure(t, Blob.class)) {
return BlobWrapper.class;
}
if (ctx.getMoreTypes().isAssignableWithErasure(t, NClob.class)) {
return NClobWrapper.class;
}
if (ctx.getMoreTypes().isAssignableWithErasure(t, Clob.class)) {
return ClobWrapper.class;
}
if (ctx.getMoreTypes().isAssignableWithErasure(t, SQLXML.class)) {
return SQLXMLWrapper.class;
}
return null;
}