比较JavaPoter ParameterSpec类型与Java8 AnnotatedType
我需要将字段或方法参数的注释类型与ParameterSpec实例进行比较。在此上下文中,参数的名称无关紧要。上下文在某种程度上与未解决的问题有关 下面的测试是绿色的,但是比较代码使用的是不太类型安全的字符串转换。谁能想出一种更安全的方法比较JavaPoter ParameterSpec类型与Java8 AnnotatedType,java,annotation-processing,javapoet,Java,Annotation Processing,Javapoet,我需要将字段或方法参数的注释类型与ParameterSpec实例进行比较。在此上下文中,参数的名称无关紧要。上下文在某种程度上与未解决的问题有关 下面的测试是绿色的,但是比较代码使用的是不太类型安全的字符串转换。谁能想出一种更安全的方法 import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedType;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Assert;
import org.junit.Test;
import com.squareup.javapoet.ParameterSpec;
@SuppressWarnings("javadoc")
public class JavaPoetTest {
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.PARAMETER, ElementType.TYPE_USE })
@interface Tag {}
public static int n;
public static @Tag int t;
public static boolean isParameterSpecSameAsAnnotatedType(ParameterSpec parameter, AnnotatedType type) {
if (!parameter.type.toString().equals(type.getType().getTypeName()))
return false;
List<String> specAnnotations = parameter.annotations.stream()
.map(a -> a.type.toString())
.collect(Collectors.toList());
List<String> typeAnnotations = Arrays.asList(type.getAnnotations()).stream()
.map(a -> a.toString().replace('$', '.').replace("()", "").replace("@", ""))
.collect(Collectors.toList());
return specAnnotations.equals(typeAnnotations);
}
@Test
public void testN() throws Exception {
AnnotatedType annotatedType = JavaPoetTest.class.getField("n").getAnnotatedType();
ParameterSpec parameterSpec = ParameterSpec.builder(int.class, "name").build();
Assert.assertTrue(isParameterSpecSameAsAnnotatedType(parameterSpec, annotatedType));
}
@Test
public void testT() throws Exception {
AnnotatedType annotatedType = JavaPoetTest.class.getField("t").getAnnotatedType();
ParameterSpec parameterSpec = ParameterSpec.builder(int.class, "name").addAnnotation(Tag.class).build();
Assert.assertTrue(isParameterSpecSameAsAnnotatedType(parameterSpec, annotatedType));
}
}
JavaPoet 1.4提供了AnnotationSpec.getAnnotation工厂方法,比较结果归结为:
public static boolean isParameterSpecSameAsAnnotatedType(ParameterSpec parameter, AnnotatedType type) {
if (!parameter.type.equals(TypeName.get(type.getType())))
return false;
List<AnnotationSpec> typeAnnotations = Arrays.asList(type.getAnnotations()).stream()
.map(AnnotationSpec::get)
.collect(Collectors.toList());
return parameter.annotations.equals(typeAnnotations);
}
JavaPoet需要一个新的API AnnotationSpec.getAnnotation,它可以将java.lang.annotation.annotation转换为AnnotationSpec。一旦存在,你就可以一部分一部分地比较。