V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
77yf77yf77yf
V2EX  ›  Java

泛型限定问题

  •  
  •   77yf77yf77yf · 2021-10-28 14:54:51 +08:00 · 1550 次点击
    这是一个创建于 902 天前的主题,其中的信息可能已经有所发展或是发生改变。
    Class<? extends A & B>这样写为何不行,有什么替代方法
    11 条回复    2021-10-28 17:36:45 +08:00
    wolfie
        1
    wolfie  
       2021-10-28 15:25:20 +08:00
    Java 不支持多继承
    B 可以为 Interface
    77yf77yf77yf
        2
    77yf77yf77yf  
    OP
       2021-10-28 15:33:59 +08:00
    @wolfie 没说清楚不好意思,A 是一个抽象类,B 是一个接口,这样写上去 idea 会报错
    hingbong
        3
    hingbong  
       2021-10-28 15:53:32 +08:00
    <T extends Object & Serializable> void a(Class<T> t) {}
    hingbong
        4
    hingbong  
       2021-10-28 15:53:45 +08:00
    @hingbong 我这么写没报错
    wolfie
        5
    wolfie  
       2021-10-28 16:01:17 +08:00
    @77yf77yf77yf #2
    检查 idea 配置 module sdk 、java compiler 版本。
    检查 抽象类 和 Interface 方法冲突
    77yf77yf77yf
        6
    77yf77yf77yf  
    OP
       2021-10-28 16:05:26 +08:00
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.METHOD})
    public @interface CacheKey {
    Class<? extends AbstractStdCacheNaming & ICacheKeyNamingStrategy> keyGen() default EntityBasedKeyNamingStrategy.class;
    ...
    }

    public abstract class AbstractStdCacheNaming {...}

    public interface ICacheKeyNamingStrategy {...}


    Class<? extends AbstractStdCacheNaming & ICacheKeyNamingStrategy> keyGen() default EntityBasedKeyNamingStrategy.class;
    这一句就报错了

    @hingbong
    hingbong
        7
    hingbong  
       2021-10-28 16:32:46 +08:00   ❤️ 1
    注解上不行
    @interface members may not have type parameters
    非注解可以
    public interface CacheKey {
    <T extends Object & Comparable<? super T>> Class<T> keyGen();
    }
    hingbong
        8
    hingbong  
       2021-10-28 16:33:20 +08:00
    77yf77yf77yf
        9
    77yf77yf77yf  
    OP
       2021-10-28 16:43:22 +08:00
    @hingbong 那对于注解有什么替代方案吗,不然只能用反射检查?
    hingbong
        10
    hingbong  
       2021-10-28 17:03:57 +08:00
    我是写 kotlin 的
    试了一下 kotlin 可以,但是那个注解到 Java 下又无法使用,只能在 kotlin 里用,Java 里我就不清楚了
    77yf77yf77yf
        11
    77yf77yf77yf  
    OP
       2021-10-28 17:36:45 +08:00
    @hingbong 好的,谢谢了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5127 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 03:53 · PVG 11:53 · LAX 20:53 · JFK 23:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.