Search code examples
javaannotation-processingjavapoet

Compare JavaPoet ParameterSpec type with Java 8 AnnotatedType


I need to compare the annotated type of a field (or method parameter) with a ParameterSpec instance. The name of the parameter does not matter in this context. The context is somewhat related to the unresolved issue 136.

The following tests are green - but the comparing code uses not so type-safe string conversions. Who can think of a more type-safe approach?

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

}

Solution

  • With JavaPoet 1.4 providing the AnnotationSpec.get(Annotation) factory method, the comparing boils down to:

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