下面列出了javax.lang.model.element.TypeElement#getSuperclass ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private boolean validateSuperClassRecursive(TypeMirror targetType, TypeMirror superClass) {
if (!(targetType instanceof DeclaredType)) {
return false;
}
if (TypeUtils.isAssignable(this.processingEnv, targetType, superClass)) {
return true;
}
TypeElement targetElement = (TypeElement)((DeclaredType)targetType).asElement();
TypeMirror targetSuper = targetElement.getSuperclass();
if (targetSuper.getKind() == TypeKind.NONE) {
return false;
}
if (this.checkMixinsFor(targetSuper, superClass)) {
return true;
}
return this.validateSuperClassRecursive(targetSuper, superClass);
}
/**
* Find all parent classes and interfaces from current class.
* It is be deprecated,now.
*/
@Deprecated
private boolean isParcelable(TypeElement currentClass) {
if (null == currentClass) {
return false;
}
for (TypeMirror mirror : currentClass.getInterfaces()) {
if (mirror.toString().equals("android.os.Parcelable")) {
return true;
}
}
final TypeMirror superClassType = currentClass.getSuperclass();
if (superClassType.getKind() == TypeKind.NONE) {
// "TypeKind.NONE" meanings currentClass=java.lang.Object
return false;
}
final TypeElement superClass = (TypeElement) mTypes.asElement(superClassType);
return isParcelable(superClass);
}
private boolean isSubtypeOfActivity(TypeMirror typeMirror) {
if ("android.app.Activity".equals(typeMirror.toString())) {
return true;
}
if (typeMirror.getKind() != TypeKind.DECLARED) {
return false;
}
DeclaredType declaredType = (DeclaredType) typeMirror;
Element element = declaredType.asElement();
if (!(element instanceof TypeElement)) {
return false;
}
TypeElement typeElement = (TypeElement) element;
TypeMirror superType = typeElement.getSuperclass();
return isSubtypeOfActivity(superType);
}
private String findViewTypeOfPresenter(TypeElement presenterElement) {
TypeElement currentClass = presenterElement;
while (currentClass != null) {
if (currentClass.getSuperclass() instanceof DeclaredType) {
List<? extends TypeMirror> superClassParameters =
((DeclaredType) currentClass.getSuperclass()).getTypeArguments();
if (superClassParameters.size() == 1) {
String type = superClassParameters.get(0).toString();
if (!"V".equals(type)) return type;
}
}
currentClass = getSuperClass(currentClass);
}
return "";
}
public static TypeElement getDeclaringClassMethod(TypeElement theClass, String methodName, TypeMirror[] args) {
TypeElement retClass = null;
if (theClass.getKind().equals(ElementKind.CLASS)) {
TypeMirror superClass = theClass.getSuperclass();
if (!superClass.getKind().equals(TypeKind.NONE))
retClass = getDeclaringClassMethod(superClass, methodName, args);
}
if (retClass == null) {
for (TypeMirror interfaceType : theClass.getInterfaces()) {
retClass = getDeclaringClassMethod(interfaceType, methodName, args);
}
}
if (retClass == null) {
Collection<? extends ExecutableElement> methods = ElementFilter.methodsIn(theClass.getEnclosedElements());
for (ExecutableElement method : methods) {
if (method.getSimpleName().toString().equals(methodName)) {
retClass = theClass;
break;
}
}
}
return retClass;
}
@Override
public Void visitType(TypeElement element, SignatureVisitor visitor) {
if (!signatureRequired(element)) {
return null;
}
for (TypeParameterElement typeParameterElement : element.getTypeParameters()) {
typeParameterElement.accept(this, visitor);
}
TypeMirror superclass = element.getSuperclass();
if (superclass.getKind() != TypeKind.NONE) {
superclass.accept(typeVisitorAdapter, visitor.visitSuperclass());
} else {
// Interface type; implicit superclass of Object
SignatureVisitor superclassVisitor = visitor.visitSuperclass();
superclassVisitor.visitClassType("java/lang/Object");
superclassVisitor.visitEnd();
}
for (TypeMirror interfaceType : element.getInterfaces()) {
interfaceType.accept(typeVisitorAdapter, visitor.visitInterface());
}
return null;
}
/**
* Given a class, return the closest visible super class.
*
* @param te the TypeElement to be interrogated
* @return the closest visible super class. Return null if it cannot
* be found..
*/
public TypeMirror getFirstVisibleSuperClass(TypeElement te) {
TypeMirror superType = te.getSuperclass();
if (isNoType(superType)) {
superType = getObjectType();
}
TypeElement superClass = asTypeElement(superType);
// skip "hidden" classes
while ((superClass != null && isHidden(superClass))
|| (superClass != null && !isPublic(superClass) && !isLinkable(superClass))) {
TypeMirror supersuperType = superClass.getSuperclass();
TypeElement supersuperClass = asTypeElement(supersuperType);
if (supersuperClass == null
|| supersuperClass.getQualifiedName().equals(superClass.getQualifiedName())) {
break;
}
superType = supersuperType;
superClass = supersuperClass;
}
if (te.asType().equals(superType)) {
return null;
}
return superType;
}
public Boolean visitType(TypeElement arg0, Void arg1) {
for (TypeParameterElement e : arg0.getTypeParameters()) {
if (stop) {
return false;
}
for (TypeMirror b : e.getBounds()) {
if (stop) {
return false;
}
if (b.accept(this, arg1)) {
return true;
}
}
}
TypeMirror superclass = arg0.getSuperclass();
if (superclass.getKind() == TypeKind.DECLARED) {
if (!((DeclaredType) superclass).asElement().getKind().isInterface()) {
return false;
}
}
return superclass.accept(this, arg1);
}
private static List<TypeElement> getAllClasses(TypeElement of) {
List<TypeElement> result = new ArrayList<>();
TypeMirror sup = of.getSuperclass();
TypeElement te = sup.getKind() == TypeKind.DECLARED ? (TypeElement) ((DeclaredType)sup).asElement() : null;
result.add(of);
if (te != null) {
result.addAll(getAllClasses(te));
} else {
if (ERR.isLoggable(ErrorManager.INFORMATIONAL)) {
ERR.log(ErrorManager.INFORMATIONAL, "te=null, t=" + of);
}
}
return result;
}
public static TypeElement getDeclaringClassMethod(TypeElement theClass, String methodName, TypeMirror[] args) {
TypeElement retClass = null;
if (theClass.getKind().equals(ElementKind.CLASS)) {
TypeMirror superClass = theClass.getSuperclass();
if (!superClass.getKind().equals(TypeKind.NONE))
retClass = getDeclaringClassMethod(superClass, methodName, args);
}
if (retClass == null) {
for (TypeMirror interfaceType : theClass.getInterfaces()) {
retClass = getDeclaringClassMethod(interfaceType, methodName, args);
}
}
if (retClass == null) {
Collection<? extends ExecutableElement> methods = ElementFilter.methodsIn(theClass.getEnclosedElements());
for (ExecutableElement method : methods) {
if (method.getSimpleName().toString().equals(methodName)) {
retClass = theClass;
break;
}
}
}
return retClass;
}
private boolean ancestorIsRetroWeibo(TypeElement type) {
while (true) {
TypeMirror parentMirror = type.getSuperclass();
if (parentMirror.getKind() == TypeKind.NONE) {
return false;
}
Types typeUtils = processingEnv.getTypeUtils();
TypeElement parentElement = (TypeElement) typeUtils.asElement(parentMirror);
if (parentElement.getAnnotation(RetroWeibo.class) != null) {
return true;
}
type = parentElement;
}
}
public TypeElement getSuperClass(TypeElement typeElement) {
if (typeElement.getKind().equals(ElementKind.CLASS)) {
TypeMirror sup = typeElement.getSuperclass();
if (!sup.getKind().equals(TypeKind.NONE))
return (TypeElement) ((DeclaredType) sup).asElement();
else
return null;
}
return env.getElementUtils().getTypeElement(Object.class.getName());
}
@Test
public void testGetSuperclassOfEnumIsEnumWithArgs() throws IOException {
compile("enum Foo { }");
TypeElement fooElement = elements.getTypeElement("Foo");
DeclaredType superclass = (DeclaredType) fooElement.getSuperclass();
TypeElement enumElement = elements.getTypeElement("java.lang.Enum");
TypeMirror expectedSuperclass = types.getDeclaredType(enumElement, fooElement.asType());
assertSameType(expectedSuperclass, superclass);
}
private void validateClassMixin(TypeElement mixin, Collection<TypeHandle> targets) {
TypeMirror superClass = mixin.getSuperclass();
for (TypeHandle target : targets) {
TypeMirror targetType = target.getType();
if (targetType != null && !this.validateSuperClass(targetType, superClass)) {
this.error("Superclass " + superClass + " of " + mixin + " was not found in the hierarchy of target class " + targetType, mixin);
}
}
}
protected void collectAncestors(TypeElement type , Set<TypeElement> ancestors,
CompilationInfo compInfo )
{
TypeMirror superclass = type.getSuperclass();
addAncestor( superclass, ancestors, compInfo);
List<? extends TypeMirror> interfaces = type.getInterfaces();
for (TypeMirror interfaze : interfaces) {
addAncestor(interfaze, ancestors, compInfo);
}
}
/**
* Checks if this AnnotatedAdapter has another AnnotatedAdapter as super class. Therfore the
* binder interface must extends from this one.
*/
public AdapterInfo getAnnotatedAdapterSuperClass(Map<String, AdapterInfo> adaptersMap) {
if (searchedForSuperAnnotatedAdapterClass) {
return superAnnotatedAdapterClass;
}
searchedForSuperAnnotatedAdapterClass = true;
// Search from bottom up along inheritance three for the fist Annotated adapter class we find
TypeElement currentClass = adapterClass;
while (currentClass != null) {
TypeMirror currentMirror = currentClass.getSuperclass();
if (currentMirror instanceof NoType || currentMirror.getKind() == TypeKind.NONE) {
// java.lang.Object has been found, there is no other super class
return null;
}
AdapterInfo superAdapter = adaptersMap.get(currentMirror.toString());
if (superAdapter != null) {
// "Cache" the found super class for performance reasons
superAnnotatedAdapterClass = superAdapter;
return superAnnotatedAdapterClass;
}
// Continue with the super class
currentClass = elementUtils.getTypeElement(currentMirror.toString());
}
return null;
}
/**
* This processes a single class that is annotated with {@link JsonType}. It verifies that the
* class is public and creates an {@link ProcessorClassData} for it.
*/
private void processClassAnnotation(Element element) {
boolean abstractClass = false;
TypeElement typeElement = (TypeElement) element;
// The annotation should be validated for an interface, but no code should be generated.
JsonType annotation = element.getAnnotation(JsonType.class);
if (element.getKind() == INTERFACE) {
return;
}
boolean isKotlin = false;
try {
Class<? extends Annotation> metaDataClass =
Class.forName("kotlin.Metadata").asSubclass(Annotation.class);
isKotlin = element.getAnnotation(metaDataClass) != null;
} catch (ClassNotFoundException e) {
// not kotlin
}
// Verify containing class visibility is not private.
if (element.getModifiers().contains(PRIVATE)) {
error(
element,
"@%s %s may not be applied to private classes. (%s.%s)",
JsonType.class.getSimpleName(),
typeElement.getQualifiedName(),
element.getSimpleName());
return;
}
if (element.getModifiers().contains(ABSTRACT)) {
abstractClass = true;
}
JsonParserClassData injector = mState.mClassElementToInjectorMap.get(typeElement);
if (injector == null) {
String parentGeneratedClassName = null;
if (!mOmitSomeMethodBodies) {
// Superclass info is only needed if we're generating method bodies.
TypeMirror superclass = typeElement.getSuperclass();
// walk up the superclass hierarchy until we find another class we know about.
while (superclass.getKind() != TypeKind.NONE) {
TypeElement superclassElement = (TypeElement) mTypes.asElement(superclass);
if (superclassElement.getAnnotation(JsonType.class) != null) {
String superclassPackageName = mTypeUtils.getPackageName(mElements, superclassElement);
parentGeneratedClassName =
superclassPackageName
+ "."
+ mTypeUtils.getPrefixForGeneratedClass(
superclassElement, superclassPackageName)
+ JsonAnnotationProcessorConstants.HELPER_CLASS_SUFFIX;
break;
}
superclass = superclassElement.getSuperclass();
}
}
boolean generateSerializer =
annotation.generateSerializer() == JsonType.TriState.DEFAULT
? mGenerateSerializers
: annotation.generateSerializer() == JsonType.TriState.YES;
String packageName = mTypeUtils.getPackageName(mElements, typeElement);
injector =
new JsonParserClassData(
packageName,
typeElement.getQualifiedName().toString(),
mTypeUtils.getClassName(typeElement, packageName),
mTypeUtils.getPrefixForGeneratedClass(typeElement, packageName)
+ JsonAnnotationProcessorConstants.HELPER_CLASS_SUFFIX,
new ProcessorClassData.AnnotationRecordFactory<String, TypeData>() {
@Override
public TypeData createAnnotationRecord(String key) {
return new TypeData();
}
},
abstractClass,
generateSerializer,
mOmitSomeMethodBodies,
parentGeneratedClassName,
annotation,
isKotlin);
mState.mClassElementToInjectorMap.put(typeElement, injector);
}
}
private static TypeName getMountType(
Elements elements, TypeElement element, EnumSet<RunMode> runMode) {
TypeElement viewType = elements.getTypeElement(ClassNames.VIEW_NAME);
TypeElement drawableType = elements.getTypeElement(ClassNames.DRAWABLE_NAME);
for (Element enclosedElement : element.getEnclosedElements()) {
if (enclosedElement.getKind() != ElementKind.METHOD) {
continue;
}
OnCreateMountContent annotation = enclosedElement.getAnnotation(OnCreateMountContent.class);
if (annotation != null) {
if (annotation.mountingType() == MountingType.VIEW) {
return ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE_VIEW;
}
if (annotation.mountingType() == MountingType.DRAWABLE) {
return ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE_DRAWABLE;
}
TypeMirror initialReturnType = ((ExecutableElement) enclosedElement).getReturnType();
if (runMode.contains(RunMode.ABI)) {
// We can't access the supertypes of the return type, so let's guess, and we'll verify
// that our guess was correct when we do a full build later.
if (initialReturnType.toString().contains("Drawable")) {
return ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE_DRAWABLE;
} else {
return ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE_VIEW;
}
}
TypeMirror returnType = initialReturnType;
while (returnType.getKind() != TypeKind.NONE && returnType.getKind() != TypeKind.VOID) {
final TypeElement returnElement = (TypeElement) ((DeclaredType) returnType).asElement();
if (returnElement.equals(viewType)) {
if (initialReturnType.toString().contains("Drawable")) {
throw new ComponentsProcessingException(
"Mount type cannot be correctly inferred from the name of "
+ element
+ ". Please specify `@OnCreateMountContent(mountingType = MountingType.VIEW)`.");
}
return ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE_VIEW;
} else if (returnElement.equals(drawableType)) {
if (!initialReturnType.toString().contains("Drawable")) {
throw new ComponentsProcessingException(
"Mount type cannot be correctly inferred from the name of "
+ element
+ ". Please specify `@OnCreateMountContent(mountingType = MountingType.DRAWABLE)`.");
}
return ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE_DRAWABLE;
}
try {
returnType = returnElement.getSuperclass();
} catch (RuntimeException e) {
throw new ComponentsProcessingException(
"Failed to get mount type for "
+ element
+ ". Try specifying `@OnCreateMountContent(mountingType = MountingType.VIEW)` (or DRAWABLE).");
}
}
}
}
return ClassNames.COMPONENT_LIFECYCLE_MOUNT_TYPE_NONE;
}
@Override
public Void visitType(TypeElement e, ClassVisitor visitor) {
if (classVisitorStarted) {
// We'll get inner class references later
return null;
}
TypeMirror superclass = e.getSuperclass();
if (superclass.getKind() == TypeKind.NONE) {
superclass = Objects.requireNonNull(elements.getTypeElement("java.lang.Object")).asType();
}
int classFileVersion = SourceVersionUtils.sourceVersionToClassFileVersion(targetVersion);
visitor.visit(
classFileVersion,
accessFlagsUtils.getAccessFlagsForClassNode(e),
descriptorFactory.getInternalName(e),
signatureFactory.getSignature(e),
descriptorFactory.getInternalName(superclass),
e.getInterfaces().stream()
.map(descriptorFactory::getInternalName)
.toArray(size -> new String[size]));
classVisitorStarted = true;
// Handle nests in Java 11+. See JEP 181 (https://openjdk.java.net/jeps/181) for details.
if (classFileVersion >= Opcodes.V11) {
if (e.getNestingKind().isNested()) {
visitNestHost(e, visitor);
} else {
visitNestMembers(e, visitor);
}
}
visitAnnotations(e, visitor::visitAnnotation);
super.visitType(e, visitor);
InnerClassesTable innerClassesTable =
new InnerClassesTable(descriptorFactory, accessFlagsUtils, e);
if (e.getKind().isClass() || classFileVersion >= Opcodes.V1_8) {
try {
generateBridges(e, visitor, innerClassesTable);
} catch (UnsupportedOperationException | CannotInferException ex) { // NOPMD
// Can't generate bridges in source-only mode
}
}
innerClassesTable.reportInnerClassReferences(visitor);
return null;
}
@Override
public void validateAccessorMethod(TypeElement classElement, InternalDomainMeta domainMeta) {
TypeElement typeElement = classElement;
TypeMirror typeMirror = classElement.asType();
for (; typeElement != null && typeMirror.getKind() != TypeKind.NONE; ) {
for (ExecutableElement method :
ElementFilter.methodsIn(typeElement.getEnclosedElements())) {
if (!method.getSimpleName().contentEquals(domainMeta.getAccessorMethod())) {
continue;
}
if (method.getModifiers().contains(Modifier.PRIVATE)) {
continue;
}
if (!method.getParameters().isEmpty()) {
continue;
}
TypeMirror returnType = method.getReturnType();
if (ctx.getMoreTypes()
.isAssignableWithErasure(
ctx.getMoreTypes().erasure(returnType), domainMeta.getValueType())) {
return;
}
TypeVariable typeVariable = ctx.getMoreTypes().toTypeVariable(returnType);
if (typeVariable != null) {
TypeMirror inferredReturnType = inferType(typeVariable, typeElement, typeMirror);
if (inferredReturnType != null) {
if (ctx.getMoreTypes()
.isAssignableWithErasure(inferredReturnType, domainMeta.getValueType())) {
return;
}
}
}
}
typeMirror = typeElement.getSuperclass();
typeElement = ctx.getMoreTypes().toTypeElement(typeMirror);
}
throw new AptException(
Message.DOMA4104,
classElement,
new Object[] {domainMeta.getAccessorMethod(), domainMeta.getValueType()});
}