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?
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) .
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));
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.
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.
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With