猿问

JavaPoet 检查 TypeName 是否是 List 的实例

在 JavaPoet 中,我可以像这样从每个类中获取一个 TypeName 作为类的示例List

TypeName TYPE_LIST = ClassName.get(List.class);

但是我现在如何检查给定的TypeName是否是 List 的实例?假设我有一个返回 a 的方法List<String>。我可以使用以下方法获取返回类型:

TypeName returnTyoe = TypeName.get(method.getReturnType());

我如何检查 tis 方法是否返回 a List?我不在乎它是否是 aList<String>我只想知道它是否至少是 aList并完全忽略通用参数。


www说
浏览 251回答 3
3回答

繁花如伊

正如您正确指出的那样,您将无法确定它是否是List<String>因为类型erasure。如果你只是想检查它是否是一个List,那么你可以这样做,return&nbsp;method.getReturnType().contains("java.util.List");

小唯快跑啊

这是我对这个问题的解决方案(非常简单):&nbsp;public static boolean isParameterizedType(Class clazz) {&nbsp; &nbsp; &nbsp; &nbsp; String simpleName = clazz.getSimpleName();&nbsp; &nbsp; &nbsp; &nbsp; return parameterizedTypeSet.contains(simpleName);&nbsp; &nbsp; }private static Set<String> parameterizedTypeSet = new HashSet<>();&nbsp; &nbsp; static {&nbsp; &nbsp; &nbsp; &nbsp; parameterizedTypeSet.add("List");&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答