Java polymorphism workaround

One limitation of Java generics is that you can’t have polymorphic data within a method. But there is a workaround of declaring a static class within a method. The Java record syntax let’s you do this without creating a new inner class object. Hopefully the inner class limitation on classes declared inside a method is lifted.

int myfunction(int x) {
   record Id() {
       static <A> id(A input) {
           A value = input;
           return value;
       }
   }
   return Id.id(x);
}

It’s a bit awkward but sometimes useful in heavily polymorphic code.

原文链接:Java polymorphism workaround

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容