Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use generic Consumer as function argument in Java?

Tags:

Code:

public void ifChangedString(String key, Consumer<String> consumer) {
    ...
    consumer.accept(getString(key));
}

public void ifChangedBoolean(String key, Consumer<Boolean> consumer) {
    ...
    consumer.accept(getBoolean(key));
}

Is it possible to make single method like public <T> void ifChanged(String key, Class<T> clazz, Consumer<T> consumer)?

Well obvious solution is public void ifChanged(String key, Consumer<Object> consumer) but I don't want to use Object as argument type, better to use several methods like above.

The problem is that for accept method I need ? super XXX and only super is Object. So is it possible at all?

like image 212
Drunya Avatar asked Jan 25 '20 16:01

Drunya


People also ask

Is Consumer a functional interface?

Interface Consumer<T> Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects. This is a functional interface whose functional method is accept(Object) .

How do you pass a Consumer to a method in Java?

The bottom line is that you have to pass in the argument when you call the accept method of the Consumer as done inside the constructor above. Show activity on this post. new ConsumerTestClass(x -> ConsumerTestClass. printString(x));

What is a Consumer function?

A Consumer is a functional interface that accepts a single input and returns no output. In layman's language, as the name suggests the implementation of this interface consumes the input supplied to it.

Where do we use Consumer in Java?

Consumer<T> is an in-built functional interface introduced in Java 8 in the java. util. function package. Consumer can be used in all contexts where an object needs to be consumed,i.e. taken as input, and some operation is to be performed on the object without returning any result.


1 Answers

You can create generic method that accepts type T object and Consumer of type T

public <T> void ifChanged(T t, Consumer<T> consumer) {

    consumer.accept(t);

}

And you can call that method by passing any object with corresponding Consumer action

ifChanged("String", s->System.out.println(s.length()));
ifChanged(10, i->System.out.println(i.toString()));
like image 153
Deadpool Avatar answered Oct 12 '22 03:10

Deadpool