12

Are there any standard generic "callback" or "function/method" types in Java, like System.Action<T> or System.Func<T,U> in .NET?

In my concrete case, I need a class that wraps a method that takes one (generic) parameter of type T and returns nothing (i.e. void).

Yes, it's easy enough to create such a class/interface for myself, but I'd prefer a standard library class if there is one.

Christian Klauser
  • 4,416
  • 3
  • 31
  • 42

2 Answers2

12

I don't believe there's anything in the standard library like this, no (at the time of writing, 2010). Other libraries have them - things like Guice's Provider<T> and Guava's Function<F, T>, Supplier<T> and Predicate<T>... so if you're using libraries already, you might want to look into what they provide in this direction.

(EDIT: As noted, those are interfaces which return things - so similar to Func<T, U> but not similar to Action<T>.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • How would any of these be equivalent? Each of the items you suggested is expected to return a value. See my [related question](http://stackoverflow.com/q/9007008/403455). – Jeff Axelrod Jan 25 '12 at 18:21
  • @glenviewjeff: They're not similar to `Action`, but they're similar to `Func`. – Jon Skeet Jan 25 '12 at 18:32
  • @glenviewjeff: You can always use [java.lang.Void](http://docs.oracle.com/javase/7/docs/api/java/lang/Void.html) if you don't need the return value. A "standardised" `Func` is better than nothing, imo. – Christian Klauser Jan 25 '12 at 23:11
  • This is why I love C# over Java. – Sachin Kainth Jul 25 '13 at 17:01
  • Java8 provides `Function` and `Consumer` as well as other set of common functional interfaces [here](https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html) that are similar to the delegates mentioned in the question. – Jämes Apr 18 '17 at 17:43
  • 1
    @ZenLulz: Indeed, it does now. I'm not going to revise all answers from 7 years ago though, I'm afraid... – Jon Skeet Apr 18 '17 at 18:09
  • No worries @JonSkeet, I commented your answer because this thread is well ranked on Google and that will be useful for the community to know that Oracle (finally) introduce them. :-) Fortunately, you can count on other members to keep your answers up-to-date, because if you had to update them all, that would be quite... time consuming with your _pretty_ high participation to SO hihi! – Jämes Apr 18 '17 at 22:12
2

Java standard library doesn't provide any such classes.

You can use Functional Java library which provides fj.F1<T, fj.Unit> which is basically equivalent of System.Action<T> from .NET.

missingfaktor
  • 90,905
  • 62
  • 285
  • 365