gson-compile/gson-compile-processor/src/main/java/io/gitlab/jfronny/gson/compile/processor/TypeHelper.java

77 lines
2.6 KiB
Java

package io.gitlab.jfronny.gson.compile.processor;
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.typeParameters.isEmpty;
}
public static boolean isGenericType(TypeMirror type) {
return type.kind == 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.typeArguments) {
if (argType.kind == 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.interfaces) {
if (typeUtils.erasure(interfaceType).toString().equals(parentClassName)) return true;
}
TypeMirror superclassType = element.superclass;
if (superclassType != null) {
if (typeUtils.erasure(superclassType).toString().equals(parentClassName)) {
return true;
} else {
return isInstance(asDeclaredType(superclassType), parentClassName, typeUtils);
}
}
return false;
}
static String getDefaultValue(TypeMirror type) {
return switch (type.kind) {
case BYTE, SHORT, INT, LONG, FLOAT, CHAR, DOUBLE -> "0";
case BOOLEAN -> "false";
default -> "null";
};
}
}