SpringMVC中的RequestMapping、GetMapping、PostMapping等是否有共同的超类?

huangapple go评论75阅读模式
英文:

SpringMVC: do RequestMapping, GetMapping, PostMapping... have a common superclass?

问题

public static void printPaths(RequestMapping mapping) {
    System.out.println(String.join(",", mapping.path()));
}

以下代码无法工作有趣的是堆栈溢出的回答者在驳斥之前不会仔细阅读问题
```java
final GetMapping getMapping = method.getAnnotation(GetMapping.class);
printPaths(getMapping);

在我像这样使用时是否存在类型 X:

public static void printPaths(X mapping) {
    System.out.println(String.join(",", mapping.path()));
}

以下代码能够正常工作吗?

// WhateverMapping 表示它可以是 RequestMapping、GetMapping、PostMapping 等等......
final WhateverMapping whateverMapping = method.getAnnotation(WhateverMapping.class);
printPaths(whateverMapping);

非常感谢。


<details>
<summary>英文:</summary>

```java
    public static void printPaths(RequestMapping mapping) {
        System.out.println(String.join(&quot;,&quot;,mapping.path()));
    }

the following code cannot work. Interestingly, stack overflow respondents will not read the question carefully before disproving of it.

        final GetMapping getMapping = method.getAnnotation(GetMapping.class);
        printPaths(getMapping);

is there a type X when I use it like this:

    public static void printPaths(X mapping) {
        System.out.println(String.join(&quot;,&quot;,mapping.path()));
    }

the following code can work well?

        //WhateverMapping means it could be RequestMapping, or GetMapping, or PostMapping, or .....
        final WhateverMapping whateverMapping = method.getAnnotation(WhateverMapping.class);
        printPaths(whaterverMappingMapping);

Thanks a lot.

答案1

得分: 0

这是不可能的,因为@GetMapping是一个组合注释,没有超类。一种解决方法是仅使用@RequestMapping,因为@GetMapping只是@RequestMapping(method=GET)的快捷方式。

GetMapping映射 = 方法.getAnnotation(GetMapping.class);
System.out.println(映射 instanceof RequestMapping); // false

英文:

This is not possible as @GetMapping is a composed annotation, there is no superclass. A workaround is to use only @RequestMapping as @GetMapping is just a shortcut for @RequestMapping(method=GET).

GetMapping mapping = method.getAnnotation(GetMapping.class);
System.out.println(mapping instanceof RequestMapping); // false

huangapple
  • 本文由 发表于 2020年8月6日 17:14:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/63280428.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定