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

61 lines
2.2 KiB
Java
Raw Normal View History

2022-11-01 11:38:37 +01:00
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.SimpleTypeVisitor14;
import javax.lang.model.util.Types;
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 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;
}
}