Java 8 add extension/default method to class

前端 未结 4 787
一向
一向 2020-12-23 11:53

I am looking for a java equivalent to the C# extension methods feature. Now I have been reading about Java 8\'s default methods, but as far as I can see, I can only add thes

4条回答
  •  长情又很酷
    2020-12-23 12:03

    C# extension methods are static and use-site, whereas Java's default methods are virtual and declaration-site.

    What I believe you are hoping for is the ability to "monkey-patch" a method into a class you do not control, but Java does not give you that (by design; it was considered and rejected.)

    Another benefit of default methods over the C# approach is that they are reflectively discoverable, and in fact from the outside, don't look any different from "regular" interface methods.

    One advantage of C#'s extension methods over Java's default methods is that with C#'s reified generics, extension methods are injected into types, not classes, so you can inject a sum() method into List.

    Above all, the main philosophical difference between Java's default methods and C#'s extension methods is that C# lets you inject methods into types you do not control (which is surely convenient for developers), whereas Java's extension methods are a first-class part of the API in which they appear (they are declared in the interface, they are reflectively discoverable, etc.) This reflects several design principles; library developers should be able to maintain control of their APIs, and library use should be transparent -- calling method x() on type Y should mean the same thing everywhere.

提交回复
热议问题