I have a Class that have a function like this:
public class Entity{
public void apply(final Function<Item, Item> function) {}
}
How do make a Call in such method?
Example:
Entity entity = new Entity();
entity.apply( ??? );
I have a Class that have a function like this:
public class Entity{
public void apply(final Function<Item, Item> function) {}
}
How do make a Call in such method?
Example:
Entity entity = new Entity();
entity.apply( ??? );
You need to pass a Function<Item, Item>
wich is a function that takes an Item
and return an Item
, imagine you have a method like
class Item {
Item doThis() {
return this;
}
}
You'll be able to do :
Function<Item, Item> fct = itm -> itm.doThis();
entity.apply(fct);
Which is the lambda form of
Function<Item, Item> fct2 = new Function<Item, Item>() {
@Override
public Item apply(Item item) {
return item.doThis();
}
};
entity.apply(fct);
Might be able to make use of Consumer<?>
public class Entity{
void consumingMethod(Consumer<Object> consumer) {
consumer.accept(this::methodToConsume)
}
void methodToConsume(Object o){
....
}
}
Object
can be replaced with a specific type, I used several types and Object
was best for me
You're working with what we call a "generic" in Java. Generics help with polymorphism (as you know) because it can take on different "types" in different contexts depending on what you want those types to be. So in your example, you can pass an Object to the method that contains whatever type you want the Generic to be. Here is an example of what your generic type (Function) might look like as a class:
public class Function<T, I> {
}
Since this type takes the types (T and I) it is essentially a "Map" in Java. Here is how you can create an Object of type Function as an example:
Function<Integer, String> function = new Function<Integer, String>();
And here is how you would pass this object to the function:
apply(function);
Notice that you will likely need to create a constructor in your Function class for the values of the Wrappers that you will want to use for this Generic. And below is what your apply method definition will look like (it doesn't need to be static, I just did this for simplicity as I was creating the pseudo code. It can be an "Instance" (non-static) method as you mentioned):
public static void apply(Function f) {
}