【发布时间】:2015-11-20 16:08:37
【问题描述】:
我需要将字段(或方法参数)的注释类型与 ParameterSpec 实例进行比较。在这种情况下,参数的名称无关紧要。上下文与未解决的issue 136 有点相关。
以下测试是绿色的 - 但比较代码使用不是那么类型安全字符串转换。谁能想到更安全的方法?
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 需要一个新的 API,
AnnotationSpec.get(Annotation),它可以将java.lang.annotation.Annotation转换为AnnotationSpec。一旦存在,您就可以逐部分比较它们。
标签: java annotation-processing javapoet