比较 JavaPoet ParameterSpec 类型与 Java 8 AnnotatedType

Compare JavaPoet ParameterSpec type with Java 8 AnnotatedType

我需要将字段(或方法参数)的注释类型与 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 1.4 提供了 AnnotationSpec.get(Annotation) 工厂方法,比较归结为:

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);
}