Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hard time understanding Java Consumer Example

I don't understand the method declaration in an example regarding the Java Consumer interface. I found this example in an online-book (Listing 11.7). It says:

class Consumers {

    public static <T> Consumer<T> measuringConsumer( Consumer<T> block){
        return t -> {
            long start = System.nanoTime();
            block.accept( t );
            long duration = System.nanoTime() - start;
            Logger.getAnonymousLogger().info("Execution time (ns): " + duration);
        };
    }
}

In the declaration what does <T> Consumer<T> mean? Shouldn't there be just Consumer<T> without the first <T>?

like image 382
question_mark Avatar asked Jan 28 '26 06:01

question_mark


1 Answers

that first <T> is used to define the bounds of the type of objects Consumer will accept.

in this particular case, the method appears to accept anything that derives from java.lang.Object, but you could use it to further constrain acceptable types by doing something like this:

public static <T extends Foo> Consumer<T> measuringConsumer(Consumer<T> block) { ... }

refer to the docs for more examples.

like image 97
homerman Avatar answered Jan 29 '26 20:01

homerman