代码之家  ›  专栏  ›  技术社区  ›  JosephH

泛型类型的构造函数上的Archunit匹配

  •  0
  • JosephH  · 技术社区  · 2 年前

    我想制定一个ArchUnit规则来接听 Spring's ResponseEntity 看起来是这样的:

    new ResponseEntity<>("No record", HttpStatus.NOT_FOUND);
    

    我试过这样一条规则:

        ArchRule rule = noClasses().should().
            callConstructor(ResponseEntity.class, String.class, HttpStatus.class).
            because("foo");
    

    但这似乎不匹配。我目前的猜测是,这是因为泛型类型,因为我将规则更改为针对非泛型类型,这似乎有效。

    我有一种感觉,使用 callConstructorWhere() 可能是解决方案的一部分,但我很难找到如何使用它的示例,而且似乎找不到文档中正确的部分。我使用的是ArchUnit 0.23.1。

    0 回复  |  直到 2 年前
        1
  •  1
  •   Manfred    2 年前

    您的猜测是正确的:泛型构造函数 ResponseEntity(T, HttpStatus) erased 参数类型 (Object, HttpStatus) callConstructor 查找这些原始类型。

    不幸的是,即使您使用 callConstructorWhere 的自定义谓词 JavaConstructorCall ,您只能访问 target owner 作为(原始) JavaClass ,但不是 JavaParameterizedType 可以容纳特定类型的参数 T = String 在你的情况下。

    所以我担心你的问题不能用当前版本的ArchUnit来解决。


    用你的 spring-web.jar 现在,您可以使用

    jar xf spring-web-*.jar
    
    javap -v org/springframework/http/ResponseEntity.class \
    | grep -A1 'ResponseEntity(T, org.springframework.http.HttpStatus)'
    

    对于 spring-web-5.3.22.jar ,我得到:

      public org.springframework.http.ResponseEntity(T, org.springframework.http.HttpStatus);
        descriptor: (Ljava/lang/Object;Lorg/springframework/http/HttpStatus;)V