下面列出了org.junit.runners.Suite#javax.lang.model.element.TypeElement 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Given a TypeElement, return the name of its type (Class, Interface, etc.).
*
* @param te the TypeElement to check.
* @param lowerCaseOnly true if you want the name returned in lower case.
* If false, the first letter of the name is capitalized.
* @return
*/
public String getTypeElementName(TypeElement te, boolean lowerCaseOnly) {
String typeName = "";
if (isInterface(te)) {
typeName = "doclet.Interface";
} else if (isException(te)) {
typeName = "doclet.Exception";
} else if (isError(te)) {
typeName = "doclet.Error";
} else if (isAnnotationType(te)) {
typeName = "doclet.AnnotationType";
} else if (isEnum(te)) {
typeName = "doclet.Enum";
} else if (isOrdinaryClass(te)) {
typeName = "doclet.Class";
}
typeName = lowerCaseOnly ? toLowerCase(typeName) : typeName;
return typeNameMap.computeIfAbsent(typeName, configuration :: getText);
}
/**
*/
private boolean hasTestableMethods(TypeElement classElem) {
List<? extends Element> enclosedElems = classElem.getEnclosedElements();
if (enclosedElems.isEmpty()) {
return false;
}
List<ExecutableElement> methods = ElementFilter.methodsIn(enclosedElems);
if (methods.isEmpty()) {
return false;
}
for (ExecutableElement method : methods) {
if (isMethodTestable(method)) {
return true;
}
}
return false;
}
public static List<Element> getAnnotatedMembers( final String annotationName,
final AnnotationModelHelper helper )
{
final List<Element> result = new LinkedList<Element>();
try {
helper.getAnnotationScanner().findAnnotations(
annotationName,
EnumSet.of(ElementKind.FIELD, ElementKind.METHOD),
new AnnotationHandler() {
@Override
public void handleAnnotation(TypeElement type,
Element element, AnnotationMirror annotation)
{
result.add(element);
}
});
}
catch (InterruptedException e) {
FieldInjectionPointLogic.LOGGER.warning("Finding annotation "+
annotationName+" was interrupted"); // NOI18N
}
return result;
}
private void addFieldToAnnotationDatabase(Element fieldElement, int level) {
Class fieldClass;
//System.out.printf("Type: %s, injection: %s \n",typeElementName, fieldName);
fieldClass = createClass(fieldElement.asType(), level);
final Set<Modifier> modifiers = fieldElement.getModifiers();
String fieldName = fieldElement.getSimpleName().toString();
TypeElement declaringClassElement = (TypeElement) fieldElement.getEnclosingElement();
String declaringClassName = declaringClassElement.getQualifiedName().toString();
final List<Annotation> annotations = extractAnnotations(fieldElement, level);
int modifiersInt = convertModifiersFromAnnotationProcessing(modifiers);
final Class<?> enclosingClass = Class.forNameSafe(declaringClassName, level + 1);
if (level == 0) {
final Class<? extends Annotation> annotationType = annotations.get(0).rnrAnnotationType();
Set<Class<?>> classes = mapAnnotationTypeToClassContainingAnnotation.get(annotationType);
if (classes == null) {
classes = new HashSet<>();
}
classes.add(enclosingClass);
mapAnnotationTypeToClassContainingAnnotation.put(annotationType, classes);
}
final Field field = new Field(fieldName, fieldClass, enclosingClass, modifiersInt, annotations);
enclosingClass.addField(field);
annotatedClassSet.add(enclosingClass);
}
@Test public void methodSignatureTest() {
Elements elements = compilationRule.getElements();
TypeElement inner = elements.getTypeElement(InnerClass.class.getCanonicalName());
ExecutableElement method = Iterables.getOnlyElement(methodsIn(inner.getEnclosedElements()));
String formatted = new MethodSignatureFormatter(compilationRule.getTypes()).format(method);
// This is gross, but it turns out that annotation order is not guaranteed when getting
// all the AnnotationMirrors from an Element, so I have to test this chopped-up to make it
// less brittle.
assertThat(formatted).contains("@Singleton");
assertThat(formatted).doesNotContain("@javax.inject.Singleton"); // maybe more importantly
assertThat(formatted)
.contains("@dagger.internal.codegen.MethodSignatureFormatterTest.OuterClass.Foo"
+ "(bar=String.class)");
assertThat(formatted).contains(" String "); // return type compressed
assertThat(formatted).contains("int, ImmutableList<Boolean>)"); // parameters compressed.
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
// System.err.println("TestProcessor.process " + roundEnv);
JavacTask task = JavacTask.instance(processingEnv);
if (++round == 1) {
switch (ak) {
case ADD_IN_PROCESSOR:
task.addTaskListener(listener);
break;
case ADD_IN_LISTENER:
addInListener(task, TaskEvent.Kind.ANALYZE, listener);
break;
}
} else if (roundEnv.processingOver()) {
switch (rk) {
case REMOVE_IN_PROCESSOR:
task.removeTaskListener(listener);
break;
case REMOVE_IN_LISTENER:
removeInListener(task, TaskEvent.Kind.GENERATE, listener);
break;
}
}
return true;
}
public static boolean isFieldAccess(TypeElement clazz) {
boolean fieldAccess = false;
boolean accessTypeDetected = false;
TypeElement typeElement = clazz;
Name qualifiedName = typeElement.getQualifiedName();
whileloop:
while (typeElement != null) {
if (isAnnotatedWith(typeElement, "javax.persistence.Entity") || isAnnotatedWith(typeElement, "javax.persistence.MappedSuperclass")) { // NOI18N
for (Element element : typeElement.getEnclosedElements()) {
if (isAnnotatedWith(element, "javax.persistence.Id") || isAnnotatedWith(element, "javax.persistence.EmbeddedId")) {
if (ElementKind.FIELD == element.getKind()) {
fieldAccess = true;
}
accessTypeDetected = true;
break whileloop;
}
}
}
typeElement = getSuperclassTypeElement(typeElement);
}
if (!accessTypeDetected) {
Logger.getLogger(JpaControllerUtil.class.getName()).log(Level.WARNING, "Failed to detect correct access type for class: {0}", qualifiedName); // NOI18N
}
return fieldAccess;
}
public void validate(CompilationInfo info) {
TypeElement test = info.getElements().getTypeElement("test.Test");
boolean foundCloneMethod = false;
boolean foundToStringMethod = false;
for (ExecutableElement ee : ElementFilter.methodsIn(test.getEnclosedElements())) {
if (ee.getSimpleName().contentEquals("clone")) {
if (ee.getParameters().isEmpty()) {
assertFalse(foundCloneMethod);
foundCloneMethod = true;
}
} else if (ee.getSimpleName().contentEquals("toString")) {
if (ee.getParameters().isEmpty()) {
assertFalse(foundToStringMethod);
foundToStringMethod = true;
}
}
}
assertTrue(foundCloneMethod);
assertTrue(foundToStringMethod);
}
private void checkSpecializes( TypeElement typeElement,
LinkedList<Element> beans, Set<Element> resultElementSet,
Set<Element> originalElements)
{
TypeElement current = typeElement;
while( current != null ){
TypeMirror superClass = current.getSuperclass();
if (!(superClass instanceof DeclaredType)) {
break;
}
if (!AnnotationObjectProvider.hasSpecializes(current, getHelper())) {
break;
}
TypeElement superElement = (TypeElement) ((DeclaredType) superClass)
.asElement();
if (originalElements.contains(superElement)) {
resultElementSet.remove(superElement);
}
beans.remove( superElement );
if ( !getResult().getTypeElements().contains( superElement)){
break;
}
current = superElement;
}
}
public static List<? extends AnnotationMirror> getClassAnnotations(JavaSource source) {
final List<? extends AnnotationMirror>[] classAnons = new List[1];
try {
source.runUserActionTask(new AbstractTask<CompilationController>() {
public void run(CompilationController controller) throws IOException {
controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
TypeElement classElement = getTopLevelClassElement(controller);
if (classElement == null) {
return;
}
classAnons[0] = controller.getElements().getAllAnnotationMirrors(classElement);
}
}, true);
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
return classAnons[0];
}
@Override
public StringBuilder visitDeclared(DeclaredType t, Boolean p) {
Element e = t.asElement();
if (e instanceof TypeElement) {
TypeElement te = (TypeElement)e;
DEFAULT_VALUE.append((p ? te.getQualifiedName() : te.getSimpleName()).toString());
Iterator<? extends TypeMirror> it = t.getTypeArguments().iterator();
if (it.hasNext()) {
DEFAULT_VALUE.append("<"); //NOI18N
while(it.hasNext()) {
visit(it.next(), p);
if (it.hasNext())
DEFAULT_VALUE.append(", "); //NOI18N
}
DEFAULT_VALUE.append(">"); //NOI18N
}
return DEFAULT_VALUE;
} else {
return DEFAULT_VALUE.append(UNKNOWN); //NOI18N
}
}
private Set<String> useProvidedTypesForServices(TypeElement typeElement, ImmutableList<TypeMirror> typesMirrors) {
List<String> wrongTypes = Lists.newArrayList();
List<String> types = Lists.newArrayList();
for (TypeMirror typeMirror : typesMirrors) {
if (typeMirror.getKind() != TypeKind.DECLARED
|| !processing().getTypeUtils().isAssignable(typeElement.asType(), typeMirror)) {
wrongTypes.add(typeMirror.toString());
} else {
types.add(typeMirror.toString());
}
}
if (!wrongTypes.isEmpty()) {
processing().getMessager().printMessage(
Diagnostic.Kind.ERROR,
"@Metainf.Service(value = {...}) contains types that are not implemented by "
+ typeElement.getSimpleName()
+ ": " + wrongTypes,
typeElement,
AnnotationMirrors.findAnnotation(typeElement.getAnnotationMirrors(), Metainf.Service.class));
}
return FluentIterable.from(types).toSet();
}
@org.netbeans.api.annotations.common.SuppressWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
public static String getMainClassName(final FileObject classFO) throws IOException {
JavaSource javaSource = JavaSource.forFileObject(classFO);
final String[] result = new String[1];
javaSource.runUserActionTask(new Task<CompilationController>() {
@Override
public void run(CompilationController controller) throws IOException {
controller.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
TypeElement classEl = SourceUtils.getPublicTopLevelElement(controller);
if (classEl != null) {
result[0] = classEl.getQualifiedName().toString();
}
}
}, true);
return result[0];
}
@Test
public void getAnnotationMirror() {
TypeElement element =
compilation.getElements().getTypeElement(AnnotatedAnnotation.class.getCanonicalName());
Optional<AnnotationMirror> documented =
MoreElements.getAnnotationMirror(element, Documented.class);
Optional<AnnotationMirror> innerAnnotation =
MoreElements.getAnnotationMirror(element, InnerAnnotation.class);
Optional<AnnotationMirror> suppressWarnings =
MoreElements.getAnnotationMirror(element, SuppressWarnings.class);
expect.that(documented).isPresent();
expect.that(innerAnnotation).isPresent();
expect.that(suppressWarnings).isAbsent();
Element annotationElement = documented.get().getAnnotationType().asElement();
expect.that(MoreElements.isType(annotationElement)).isTrue();
expect.that(MoreElements.asType(annotationElement).getQualifiedName().toString())
.isEqualTo(Documented.class.getCanonicalName());
annotationElement = innerAnnotation.get().getAnnotationType().asElement();
expect.that(MoreElements.isType(annotationElement)).isTrue();
expect.that(MoreElements.asType(annotationElement).getQualifiedName().toString())
.isEqualTo(InnerAnnotation.class.getCanonicalName());
}
private int writeExtensions(
TypeElement type,
ExtensionContext context,
ImmutableList<AutoValueExtension> applicableExtensions) {
int writtenSoFar = 0;
for (AutoValueExtension extension : applicableExtensions) {
String parentFqName = generatedSubclassName(type, writtenSoFar + 1);
String parentSimpleName = TypeSimplifier.simpleNameOf(parentFqName);
String classFqName = generatedSubclassName(type, writtenSoFar);
String classSimpleName = TypeSimplifier.simpleNameOf(classFqName);
boolean isFinal = (writtenSoFar == 0);
String source = extension.generateClass(context, classSimpleName, parentSimpleName, isFinal);
if (source != null) {
source = Reformatter.fixup(source);
writeSourceFile(classFqName, source, type);
writtenSoFar++;
}
}
return writtenSoFar;
}
public ExtendedTypeElement getAnyTypeElement(TypeMirror typeMirror) {
boolean isArrayElement = false;
boolean isGenericElement = false;
Dual<TypeElement, Boolean> typeElement = getTypeElement(typeMirror);
if (typeElement == null) {
if (typeMirror instanceof ArrayType) {
try {
ArrayType arrayType = (ArrayType) typeMirror;
typeElement = getTypeElement(arrayType.getComponentType());
isArrayElement = true;
} catch (Exception e) {
}
} else {
typeElement = Dual.create(getGenericTypeElement(typeMirror), false);
isGenericElement = true;
}
}
return new ExtendedTypeElement(typeElement, typeMirror, isArrayElement, isGenericElement);
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
if ( value instanceof DefaultMutableTreeNode ) {
value = ((DefaultMutableTreeNode)value).getUserObject();
}
String name;
String toolTip;
Icon icon;
if (value instanceof TypeElement) {
TypeElement te = (TypeElement) value;
name = getDisplayName(te);
toolTip = getToolTipText(te);
icon = UiUtils.getElementIcon( te.getKind(), te.getModifiers() );
}
else {
name = "??";
toolTip = name = (value == null ? "NULL" : value.toString());
icon = null;
}
JLabel comp = (JLabel)renderer.getListCellRendererComponent( list, value, index, isSelected, cellHasFocus );
comp.setText( name );
comp.setToolTipText(toolTip);
if (icon != null) {
comp.setIcon(icon);
}
// if ( index % 2 > 0 ) {
// comp.setBackground( list.getBackground().darker() ); // Too dark
// comp.setOpaque( true );
// }
return comp;
}
public static VariableElement getValueMember(TypeElement type) {
VariableElement member = null;
for (VariableElement field : ElementFilter.fieldsIn(type.getEnclosedElements())) {
if ("value".equals(field.getSimpleName().toString())) {
member = field;
break;
}
}
if (member == null && type.getKind().equals(ElementKind.CLASS))
member = getValueMember(type.getSuperclass());
return member;
}
public boolean run(DocletEnvironment root) {
Set<TypeElement> classes = ElementFilter.typesIn(root.getIncludedElements());
if (classes.size() != 1)
throw new Error("1 " + Arrays.asList(classes));
TypeElement self = classes.iterator().next();
DocTrees trees = root.getDocTrees();
DocCommentTree docCommentTree = trees.getDocCommentTree(self);
String c = docCommentTree.getFullBody().toString();
System.out.println("\"" + c + "\"");
return c.equals("First sentence.\n0\n 1\n 2\n 3\n 4\n 5");
}
public static VariableElement getField(TypeElement clazz, String fieldName) {
for (VariableElement field : ElementFilter.fieldsIn(clazz.getEnclosedElements())) {
if (field.getSimpleName().contentEquals(fieldName)) {
return field;
}
}
return null;
}
@Test
public void methodParams_NumberList() {
TypeElement xCollection = getTypeElement(XCollection.class);
TypeElement xNumberList = getTypeElement(XNumberList.class);
TypeElement number = getTypeElement(Number.class);
ExecutableElement add = getMethod(xCollection, "add", TypeKind.TYPEVAR);
List<TypeMirror> params = explicitOverrides.erasedParameterTypes(add, xNumberList);
List<TypeMirror> expectedParams = ImmutableList.of(number.asType());
assertTypeListsEqual(params, expectedParams);
}
@Test
public void testGetSuperclassObjectSuperclassIsObject() throws IOException {
compile("class Foo extends java.lang.Object { }");
TypeElement fooElement = elements.getTypeElement("Foo");
DeclaredType superclass = (DeclaredType) fooElement.getSuperclass();
TypeElement objectElement = elements.getTypeElement("java.lang.Object");
assertSame(objectElement, superclass.asElement());
}
@Override
public final boolean process(
Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (!testsRan) {
testsRan = true;
typeUtil = processingEnv.getTypeUtils();
runTests();
}
return false;
}
public Map<TypeElement, BuilderGenerator> findAndParseTargets(RoundEnvironment roundEnv) {
Map<TypeElement, BuilderGenerator> targetMap = new LinkedHashMap<TypeElement, BuilderGenerator>();
// @BundleBuilder
processBundleBuilder(targetMap, roundEnv);
// @IntentBuilder
processIntentBuilder(targetMap, roundEnv);
// @FragmentBuilder
processFragmentBuilder(targetMap, roundEnv);
return targetMap;
}
private ImmutableList<AnnotationMirror> propertyFieldAnnotations(
TypeElement type, ExecutableElement method) {
if (!hasAnnotationMirror(method, COPY_ANNOTATIONS_NAME)) {
return ImmutableList.of();
}
ImmutableSet<String> excludedAnnotations =
ImmutableSet.<String>builder()
.addAll(getExcludedAnnotationClassNames(method))
.add(Override.class.getCanonicalName())
.build();
// We need to exclude type annotations from the ones being output on the method, since
// they will be output as part of the field's type.
Set<String> returnTypeAnnotations =
getReturnTypeAnnotations(method, this::annotationAppliesToFields);
Set<String> nonFieldAnnotations =
method
.getAnnotationMirrors()
.stream()
.map(a -> a.getAnnotationType().asElement())
.map(MoreElements::asType)
.filter(a -> !annotationAppliesToFields(a))
.map(e -> e.getQualifiedName().toString())
.collect(toSet());
Set<String> excluded =
ImmutableSet.<String>builder()
.addAll(excludedAnnotations)
.addAll(returnTypeAnnotations)
.addAll(nonFieldAnnotations)
.build();
return annotationsToCopy(type, method, excluded);
}
@Test
public void testNoTreeOrPathForPrecompiledCode() throws IOException {
compile("class Foo { }");
TypeElement stringElement = elements.getTypeElement("java.lang.String");
assertNull(trees.getTree(stringElement));
assertNull(trees.getPath(stringElement));
}
public void checkMethodReturnType(final TypeElement annotationElement, final ExecutableElement methodElement)
{
final TypeMirror returnType = methodElement.getReturnType();
if (!(returnType.getKind() == TypeKind.VOID || isValidType(returnType, true)))
{
processingEnv.getMessager()
.printMessage(Diagnostic.Kind.ERROR,
"@"
+ annotationElement.getSimpleName()
+ " cannot be applied to methods with return type "
+ returnType.toString(),
methodElement
);
}
}
/**
* Construct a new ConstructorWriterImpl.
*
* @param writer The writer for the class that the constructors belong to.
* @param typeElement the class being documented.
*/
public ConstructorWriterImpl(SubWriterHolderWriter writer, TypeElement typeElement) {
super(writer, typeElement);
VisibleMemberMap visibleMemberMap = configuration.getVisibleMemberMap(
typeElement,
VisibleMemberMap.Kind.CONSTRUCTORS);
List<Element> constructors = visibleMemberMap.getMembers(typeElement);
for (Element constructor : constructors) {
if (utils.isProtected(constructor) || utils.isPrivate(constructor)) {
setFoundNonPubConstructor(true);
}
}
}
public static Collection<String> extractAnnotationNames(Element elem) {
Collection<String> annotationsOnElement = new LinkedList<String>();
for (AnnotationMirror ann : elem.getAnnotationMirrors()) {
TypeMirror annType = ann.getAnnotationType();
Element typeElem = ((DeclaredType) annType).asElement();
String typeName = ((TypeElement) typeElem).getQualifiedName().toString();
annotationsOnElement.add(typeName);
}
return annotationsOnElement;
}
private Set<TypeElement> collectTypes(RoundEnvironment roundEnv,
Predicate<TypeElement> typeSelectionCondition) {
Set<TypeElement> types = new HashSet<>();
for (TypeElement type : ElementFilter.typesIn(roundEnv.getRootElements())) {
collectTypes(type, types, typeSelectionCondition);
}
return types;
}