Is it possible to do something like this in Java
private ? /* (I dont know what Class to use) */ shortcutToMethod = redundantMethod(game.getGraphics());
So instead of calling redundantMethod(game.getGraphics().doThisMethod());
I could just do shortCutToMethod.doThisMethod();
Is this possible?
Java 8 has introduced the idea of a Functional Interface, which allows you to essentially assign methods to variables. It includes a number of commonly-used interfaces as well.
Yeah you can do that. You have the Method class.
The only requirement is that is must have a single abstract method.
The scope of a private member (variable or method) is restricted only within the class in which it is defined. It cannot be accessed outside the class in which it is defined.
In Java, there are various ways. If you take a look at java.util.function
package, you can see
Function
: Takes one argument, produces one resultConsumer
: Takes one argument, produces nothing.BiConsumer
: Takes two arguments, produces nothing.Supplier
: Takes no argument, produces one result.Predicate
: Boolean value function of one argumentYou can used them as inputs for your method and execute it within.
Java 8 has introduced the idea of a Functional Interface, which allows you to essentially assign methods to variables. It includes a number of commonly-used interfaces as well.
Common examples:
Consumer<T>
- a method that takes in T
and returns void
Function<T, R>
- a method that takes in T
and returns R
Supplier<R>
- a method that takes no arguments and returns R
Runnable
- a method that takes no arguments and returns void
Predicate<T>
- a method that takes in T
and returns boolean
In your case, you appear to be after a Runnable
:
Runnable shortcutToMethod = () -> redundantMethod(game.getGraphics());
shortcutToMethod.run();
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