77 lines
2.6 KiB
Java
77 lines
2.6 KiB
Java
package io.gitlab.jfronny.gson.compile.processor.core;
|
|
|
|
import javax.lang.model.element.Element;
|
|
import javax.lang.model.element.TypeElement;
|
|
import javax.lang.model.type.*;
|
|
import javax.lang.model.util.*;
|
|
import java.util.*;
|
|
|
|
public class TypeHelper {
|
|
public static boolean isComplexType(TypeMirror type, Types typeUtils) {
|
|
Element element = typeUtils.asElement(type);
|
|
if (!(element instanceof TypeElement typeElement)) return false;
|
|
return !typeElement.getTypeParameters().isEmpty();
|
|
}
|
|
|
|
public static boolean isGenericType(TypeMirror type) {
|
|
return type.getKind() == TypeKind.TYPEVAR;
|
|
}
|
|
|
|
public static List<? extends TypeMirror> getGenericTypes(TypeMirror type) {
|
|
DeclaredType declaredType = asDeclaredType(type);
|
|
if (declaredType == null) {
|
|
return Collections.emptyList();
|
|
}
|
|
ArrayList<TypeMirror> result = new ArrayList<>();
|
|
for (TypeMirror argType : declaredType.getTypeArguments()) {
|
|
if (argType.getKind() == TypeKind.TYPEVAR) {
|
|
result.add(argType);
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
public static DeclaredType asDeclaredType(TypeMirror type) {
|
|
return type.accept(new SimpleTypeVisitor14<>() {
|
|
@Override
|
|
public DeclaredType visitDeclared(DeclaredType t, Object o) {
|
|
return t;
|
|
}
|
|
}, null);
|
|
}
|
|
|
|
public static ArrayType asArrayType(TypeMirror type) {
|
|
return type.accept(new TypeKindVisitor14<>() {
|
|
@Override
|
|
public ArrayType visitArray(ArrayType t, Object o) {
|
|
return t;
|
|
}
|
|
}, null);
|
|
}
|
|
|
|
public static boolean isInstance(DeclaredType type, String parentClassName, Types typeUtils) {
|
|
if (type == null) return false;
|
|
TypeElement element = (TypeElement) type.asElement();
|
|
for (TypeMirror interfaceType : element.getInterfaces()) {
|
|
if (typeUtils.erasure(interfaceType).toString().equals(parentClassName)) return true;
|
|
}
|
|
TypeMirror superclassType = element.getSuperclass();
|
|
if (superclassType != null) {
|
|
if (typeUtils.erasure(superclassType).toString().equals(parentClassName)) {
|
|
return true;
|
|
} else {
|
|
return isInstance(asDeclaredType(superclassType), parentClassName, typeUtils);
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
public static String getDefaultValue(TypeMirror type) {
|
|
return switch (type.getKind()) {
|
|
case BYTE, SHORT, INT, LONG, FLOAT, CHAR, DOUBLE -> "0";
|
|
case BOOLEAN -> "false";
|
|
default -> "null";
|
|
};
|
|
}
|
|
}
|