下面列出了javax.lang.model.type.IntersectionType#javax.lang.model.type.DeclaredType 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void verifyTargetType() {
TypeMirror expectedType = findExpectedType(pathToNewClassTree);
if (!Utilities.isValidType(expectedType)) {
foundErroneousTargetType = true;
return;
}
TypeMirror erasedExpectedType = info.getTypes().erasure(expectedType);
TreePath pathForClassIdentifier = new TreePath(pathToNewClassTree, newClassTree.getIdentifier());
TypeMirror lambdaType = info.getTrees().getTypeMirror(pathForClassIdentifier);
lambdaType = info.getTypes().erasure(lambdaType);
foundAssignmentToSupertype = !info.getTypes().isSameType(erasedExpectedType, lambdaType);
if (erasedExpectedType.getKind() == TypeKind.DECLARED) {
TypeElement te = (TypeElement)((DeclaredType)erasedExpectedType).asElement();
TypeMirror tt = (DeclaredType)te.asType();
if (tt.getKind() == TypeKind.DECLARED && !((DeclaredType)tt).getTypeArguments().isEmpty()) {
foundAssignmentToRawType = info.getTypes().isSameType(erasedExpectedType, expectedType);
}
}
}
protected void validateSerializer(Element element, Class<? extends Annotation> annotation, TypeMirror serializer, Class abstractSerializer) {
if (serializer == null) {
return;
}
Element absSerializerElement = elements.getTypeElement(abstractSerializer.getName());
if (absSerializerElement == null) {
throw new IllegalStateException(String.format("Unable to find %s type", abstractSerializer.getName()));
}
TypeMirror absSerializerMirror = absSerializerElement.asType();
if (!types.isAssignable(serializer, types.erasure(absSerializerMirror))) {
throw new IllegalStateException(String.format("@%s value must extend %s", annotation.getName(), abstractSerializer.getName()));
}
TypeMirror elementType = element.asType();
for (TypeMirror superType : types.directSupertypes(serializer)) {
if (types.isAssignable(superType, types.erasure(absSerializerMirror)) && superType instanceof DeclaredType) {
if (types.isSameType(((DeclaredType) superType).getTypeArguments().get(0), elementType)) {
return;
} else {
throw new IllegalStateException(String.format("Serializer T must be of type %s", elementType.toString()));
}
}
}
throw new IllegalStateException(String.format("%s must extend %s", serializer.toString(), absSerializerMirror.toString()));
}
protected boolean classImplementsSei(TypeElement classElement, TypeElement interfaceElement) {
for (TypeMirror interfaceType : classElement.getInterfaces()) {
if (((DeclaredType) interfaceType).asElement().equals(interfaceElement))
return true;
}
List<ExecutableElement> classMethods = getClassMethods(classElement);
boolean implementsMethod;
for (ExecutableElement interfaceMethod : ElementFilter.methodsIn(interfaceElement.getEnclosedElements())) {
implementsMethod = false;
for (ExecutableElement classMethod : classMethods) {
if (sameMethod(interfaceMethod, classMethod)) {
implementsMethod = true;
classMethods.remove(classMethod);
break;
}
}
if (!implementsMethod) {
builder.processError(WebserviceapMessages.WEBSERVICEAP_METHOD_NOT_IMPLEMENTED(interfaceElement.getSimpleName(), classElement.getSimpleName(), interfaceMethod), interfaceMethod);
return false;
}
}
return true;
}
private void appendAnnotation(StringBuilder sb, AnnotationMirror annotationDesc, boolean topLevel) {
DeclaredType annotationType = annotationDesc.getAnnotationType();
if (annotationType != null && (!topLevel || isDocumented(annotationType))) {
appendType(sb, annotationType, false, false, true);
Map<? extends ExecutableElement, ? extends AnnotationValue> values = annotationDesc.getElementValues();
if (!values.isEmpty()) {
sb.append('('); //NOI18N
for (Iterator<? extends Map.Entry<? extends ExecutableElement, ? extends AnnotationValue>> it = values.entrySet().iterator(); it.hasNext();) {
Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> value = it.next();
createLink(sb, value.getKey(), value.getKey().getSimpleName());
sb.append('='); //NOI18N
appendAnnotationValue(sb, value.getValue());
if (it.hasNext())
sb.append(","); //NOI18N
}
sb.append(')'); //NOI18N
}
if (topLevel)
sb.append("<br>"); //NOI18N
}
}
@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 void generateSubTypesDeserializers(TypeMirror beanType, String packageName) {
SubTypesInfo subTypesInfo= Type.getSubTypes(beanType);
for (Map.Entry<String, TypeMirror> subtypeEntry: subTypesInfo.getSubTypes().entrySet()) {
// @JsonTypeInfo and @JsonSubTypes must be used only on non generic types
// This limitation is imposed by the the the java.land.model API, which does
// not allow to retrieve interface(s) for given class (i.e. using getSupperClass()).
// That limits the possibilities to inspect interface type parameters. Even
// beanType is TypeMirror for base interface (i.e. annotated with @JsonTypeInfo and @JsonSubTypes)
// with specified type arguments, we can not match them against the
// type parameters of the subtype retrieved by @JsonSubTypes.
if (
!((DeclaredType)beanType).getTypeArguments().isEmpty()
|| !((DeclaredType)((DeclaredType)subtypeEntry.getValue()).asElement().asType()).getTypeArguments().isEmpty())
throw new RuntimeException("@JsonSubTypes and &JsonTypeInfo can be used only on non-generic Java types");
new DeserializerGenerator().generate(packageName, subtypeEntry.getValue());
}
}
public static TypeMirror getHolderValueType(TypeMirror type, TypeElement defHolder, ProcessingEnvironment env) {
TypeElement typeElement = getDeclaration(type);
if (typeElement == null)
return null;
if (isSubElement(typeElement, defHolder)) {
if (type.getKind().equals(TypeKind.DECLARED)) {
Collection<? extends TypeMirror> argTypes = ((DeclaredType) type).getTypeArguments();
if (argTypes.size() == 1) {
return argTypes.iterator().next();
} else if (argTypes.isEmpty()) {
VariableElement member = getValueMember(typeElement);
if (member != null) {
return member.asType();
}
}
}
}
return null;
}
static void findQualifiers(Element element ,
AnnotationModelHelper helper , boolean event ,
AnnotationHandleStrategy strategy )
{
List<? extends AnnotationMirror> allAnnotationMirrors =
helper.getCompilationController().getElements().
getAllAnnotationMirrors( element );
for (AnnotationMirror annotationMirror : allAnnotationMirrors) {
DeclaredType annotationType = annotationMirror
.getAnnotationType();
if ( annotationType == null || annotationType.getKind() == TypeKind.ERROR){
continue;
}
TypeElement annotationElement = (TypeElement) annotationType
.asElement();
if (annotationElement!= null && isQualifier(annotationElement,
helper , event ))
{
strategy.handleAnnotation(annotationMirror , annotationElement );
}
}
}
@Override
public DefaultAnalysis createAnalysis(InvocationContext<TypeMirror> context)
throws UnknownTypeException {
// boxed primitives have different names (at least for int)
CharSequence typeName;
final TypeMirror refinedMirror = context.field.refinedMirror();
if (refinedMirror instanceof DeclaredType) {
// we are boxed
typeName = this.type == Type.UNBOXED
? toCapitalCase(types().unboxedType(refinedMirror).getKind().name())
: ((DeclaredType) refinedMirror).asElement().getSimpleName();
} else {
// we are unboxed
typeName = this.type == Type.BOXED
? types().boxedClass((PrimitiveType) refinedMirror).getSimpleName()
: toCapitalCase(refinedMirror.getKind().name());
}
String methodName = (suffix != null) ? (typeName.toString() + suffix) : typeName.toString();
return DefaultAnalysis.of(this, methodName, context);
}
private void update( List<VariableElement> vars ,
CompilationController controller)
{
DefaultMutableTreeNode root = new DefaultMutableTreeNode();
for (VariableElement var : vars) {
FileObject fileObject = SourceUtils.getFile(ElementHandle
.create(var), controller.getClasspathInfo());
InjectableTreeNode<Element> node =
new InjectableTreeNode<Element>(fileObject, var,
(DeclaredType)controller.getElementUtilities().
enclosingTypeElement(var).asType(), false,controller);
root.add( node );
}
setRoot(root);
}
public static TypeMirror getHolderValueType(TypeMirror type, TypeElement defHolder, ProcessingEnvironment env) {
TypeElement typeElement = getDeclaration(type);
if (typeElement == null)
return null;
if (isSubElement(typeElement, defHolder)) {
if (type.getKind().equals(TypeKind.DECLARED)) {
Collection<? extends TypeMirror> argTypes = ((DeclaredType) type).getTypeArguments();
if (argTypes.size() == 1) {
return argTypes.iterator().next();
} else if (argTypes.isEmpty()) {
VariableElement member = getValueMember(typeElement);
if (member != null) {
return member.asType();
}
}
}
}
return null;
}
/**
* Criteria templates are always generated as top-level class (separate file).
* Construct criteria name from {@linkplain TypeMirror}
*
* @return fully qualified criteria (template) class name
*/
private static String topLevelCriteriaClassName(TypeMirror type) {
DeclaredType declaredType = MoreTypes.asDeclared(type);
Element element = declaredType.asElement();
do {
element = element.getEnclosingElement();
} while (element.getKind() != ElementKind.PACKAGE);
String packagePrefix = "";
if (!element.getSimpleName().contentEquals("")) {
packagePrefix = MoreElements.asPackage(element).getQualifiedName() + ".";
}
// package name + type name + "CriteriaTemplate"
return packagePrefix + declaredType.asElement().getSimpleName().toString() + "CriteriaTemplate";
}
@Override
public StringBuilder visitWildcard(WildcardType t, Boolean p) {
DEFAULT_VALUE.append("?"); //NOI18N
TypeMirror bound = t.getSuperBound();
if (bound == null) {
bound = t.getExtendsBound();
if (bound != null) {
DEFAULT_VALUE.append(" extends "); //NOI18N
if (bound.getKind() == TypeKind.WILDCARD)
bound = ((WildcardType)bound).getSuperBound();
visit(bound, p);
} else {
bound = SourceUtils.getBound(t);
if (bound != null && (bound.getKind() != TypeKind.DECLARED || !((TypeElement)((DeclaredType)bound).asElement()).getQualifiedName().contentEquals("java.lang.Object"))) { //NOI18N
DEFAULT_VALUE.append(" extends "); //NOI18N
visit(bound, p);
}
}
} else {
DEFAULT_VALUE.append(" super "); //NOI18N
visit(bound, p);
}
return DEFAULT_VALUE;
}
private static KindOfType detectKind(CompilationInfo info, TypeMirror tm) {
if (tm.getKind().isPrimitive()) {
return KindOfType.valueOf(tm.getKind().name());
}
if (tm.getKind() == TypeKind.ARRAY) {
return ((ArrayType) tm).getComponentType().getKind().isPrimitive() ? KindOfType.ARRAY_PRIMITIVE : KindOfType.ARRAY;
}
if (tm.getKind() == TypeKind.DECLARED) {
Types t = info.getTypes();
TypeElement en = info.getElements().getTypeElement("java.lang.Enum");
if (en != null) {
if (t.isSubtype(tm, t.erasure(en.asType()))) {
return KindOfType.ENUM;
}
}
if (((DeclaredType) tm).asElement().getKind().isClass() && ((TypeElement) ((DeclaredType) tm).asElement()).getQualifiedName().contentEquals("java.lang.String")) {
return KindOfType.STRING;
}
}
return KindOfType.OTHER;
}
private LightCycleBinder findParent(Set<String> erasedTargetNames, TypeMirror type) {
if (type.getKind() == TypeKind.NONE) {
return LightCycleBinder.EMPTY;
}
final TypeElement typeElement = (TypeElement) ((DeclaredType) type).asElement();
if (erasedTargetNames.contains(typeElement.toString())) {
final String parentWithLightCycle = elementUtils.getBinaryName(typeElement).toString();
return LightCycleBinder.forParent(binderName(parentWithLightCycle));
}
return findParent(erasedTargetNames, typeElement.getSuperclass());
}
private static void appendType(FragmentBuilder fb, TypeMirror type, boolean varArg) {
switch (type.getKind()) {
case ARRAY:
appendType(fb, ((ArrayType) type).getComponentType(), false);
fb.append(varArg ? "..." : "[]"); // NOI18N
break;
case DECLARED:
fb.append(((TypeElement) ((DeclaredType) type).asElement()).getQualifiedName());
break;
default:
fb.append(type.toString());
}
}
private boolean isJavaLangObject(TypeMirror type) {
if (type.getKind() != TypeKind.DECLARED) {
return false;
}
DeclaredType declaredType = (DeclaredType) type;
TypeElement typeElement = (TypeElement) declaredType.asElement();
return typeElement.getQualifiedName().contentEquals("java.lang.Object");
}
public TypeMirror erasure(TypeMirror t) {
Types tu = env.getTypeUtils();
t = tu.erasure(t);
if (t.getKind().equals(TypeKind.DECLARED)) {
DeclaredType dt = (DeclaredType)t;
if (!dt.getTypeArguments().isEmpty())
return tu.getDeclaredType((TypeElement) dt.asElement());
}
return t;
}
private String doGetName( Element original , Element element ){
List<? extends AnnotationMirror> annotations = getModel().getHelper().
getCompilationController().getElements().getAllAnnotationMirrors(
element);
for (AnnotationMirror annotationMirror : annotations) {
DeclaredType type = annotationMirror.getAnnotationType();
TypeElement annotationElement = (TypeElement)type.asElement();
if ( NAMED_QUALIFIER_ANNOTATION.contentEquals(
annotationElement.getQualifiedName()))
{
return getNamedName( original , annotationMirror );
}
}
return null;
}
/**
* Returns the functional type accepted by {@code methodName} on {@code type}, assignable to
* {@code prototype}, or {@code prototype} itself if no such method has been declared.
*
* <p>Used to allow the user to override the functional interface used on builder methods,
* e.g. to force boxing, or to use Guava types.
*/
public static FunctionalType functionalTypeAcceptedByMethod(
DeclaredType type,
String methodName,
FunctionalType prototype,
Elements elements,
Types types) {
return functionalTypesAcceptedByMethod(type, methodName, elements, types)
.stream()
.filter(functionalType -> isAssignable(functionalType, prototype, types))
.findAny()
.orElse(prototype);
}
/**
* 获取参数的具体类型
*/
private DeclaredType getMapOrCollectionImp(VariableElement variableElement) {
final DeclaredType declaredType = AutoUtils.getDeclaredType(variableElement.asType());
if (!declaredType.asElement().getModifiers().contains(Modifier.ABSTRACT)) {
// 声明类型是具体类型
return declaredType;
}
if (processor.isEnumMap(declaredType) || processor.isEnumSet(declaredType)) {
// 声明类型是EnumMap 或 EnumSet
return declaredType;
}
return (DeclaredType) processor.getFieldImplAnnotationValue(variableElement);
}
private TypeMirror toUnboundDeclaredType(TypeMirror mirror) {
if (mirror.getKind() != TypeKind.DECLARED)
return mirror;
final List<? extends TypeMirror> types = getGenericTypes(mirror);
if (types.isEmpty())
return mirror;
TypeElement lhsElement = (TypeElement) ((DeclaredType) mirror).asElement();
return this.types.getDeclaredType(lhsElement, synthesizeUnboundType(types.size()));
}
@Override
public TypeElement visitDeclared(DeclaredType t, Void ignored) {
return t.asElement().accept(new SimpleElementVisitor7<TypeElement, Void>() {
@Override
public TypeElement visitType(TypeElement e, Void aVoid) {
return e;
}
}, null);
}
private @Nullable TypeElement getSuperClass(TypeElement typeElement) {
TypeMirror type = typeElement.getSuperclass();
if (type.getKind() == TypeKind.NONE) {
return null;
}
return (TypeElement) ((DeclaredType) type).asElement();
}
@Override
public DeclaredType getDeclaredType(TypeElement typeElem, TypeMirror... typeArgs) {
requireNonNull(typeElem);
ImmutableList.Builder<Type> args = ImmutableList.builder();
for (TypeMirror t : typeArgs) {
args.add(asTurbineType(t));
}
TurbineTypeElement element = (TurbineTypeElement) typeElem;
return (DeclaredType)
factory.asTypeMirror(
ClassTy.create(
ImmutableList.of(
SimpleClassTy.create(element.sym(), args.build(), ImmutableList.of()))));
}
@Override
public Void visitDeclared(DeclaredType t, Types types) {
t.asElement().getKind(); // ensure class exists
for (TypeMirror st: types.directSupertypes(t))
visit(st, types);
return null;
}
private String getTypeName(Element typeElement) {
String injectedClassName = null;
final TypeMirror fieldTypeMirror = typeElement.asType();
if (fieldTypeMirror instanceof DeclaredType) {
injectedClassName = ((TypeElement) ((DeclaredType) fieldTypeMirror).asElement()).getQualifiedName().toString();
} else if (fieldTypeMirror instanceof PrimitiveType) {
injectedClassName = fieldTypeMirror.toString();
} else if (fieldTypeMirror instanceof ArrayType) {
injectedClassName = ((ArrayType) fieldTypeMirror).getComponentType().toString() + "[]";
}
return injectedClassName;
}
@Override
public DeclaredType getDeclaredType(DeclaredType containing, TypeElement typeElem, TypeMirror... typeArgs) {
if (isMissing(containing)) {
throw new IllegalArgumentException("Invalid containing type.");
}
if (typeElem instanceof MissingTypeElement) {
throw new IllegalArgumentException("Invalid type element.");
}
for (TypeMirror t : typeArgs) {
if (isMissing(t)) {
throw new IllegalArgumentException("Invalid type arguments.");
}
}
return IgnoreCompletionFailures.in(types::getDeclaredType, containing, typeElem, typeArgs);
}
private TypeMirror getParameterType( TypeMirror type ){
if ( type instanceof DeclaredType ){
List<? extends TypeMirror> typeArguments = ((DeclaredType)type).getTypeArguments();
if (typeArguments.isEmpty()) {
return null;
}
return typeArguments.get(0);
}
return null;
}
public boolean isParameterizedType(TypeMirror typeMirror) {
if (typeMirror != null && typeMirror.getKind().equals(TypeKind.DECLARED)) {
DeclaredType d = (DeclaredType) typeMirror;
return !d.getTypeArguments().isEmpty();
}
return false;
}