【问题标题】:Compare JavaPoet ParameterSpec type with Java 8 AnnotatedType将 JavaPoet ParameterSpec 类型与 Java 8 AnnotatedType 进行比较
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-01-31
    • 2020-11-15
    • 2023-03-22
    • 2019-05-28
    • 2019-11-28
    • 1970-01-01
    • 2013-09-14
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多