I have 3 methods which does the same thing but at the end the 3 methods call a diff method. So instead of having 3 methods, I want to have a single method which will accept a method as parameter which it will call at the end
How can I do this please, I tried having a look at the java reflection that did not work, Not sure if interfaces is the right way for this.
please suggest
Thanks
R
class A {
doSameThingA(int x) {
//do same thing with x
methodA()
}
doSameThingB(int x) {
//do same thing with x
methodB()
}
doSameThingC(int x) {
//do same thing with x
methodC()
}
//I WANT TO WRITE A SINGLE FUNCTION replacing the above three
doSameThing(int x, Method method) {
//do same thing with x
method()
}
}
An operator exists in java known as the double colon operator. It is also known as the method reference operator because it refers to methods and this feature I believe will allow you to solve your problem by parameterizing your method. Kind of like lambdas.
class A {
public static void main(String... args) {
new A().doSameThing(1, MethodClass::printSomething);
}
void doSameThing(int x, Runnable method) {
method.run();
}
}
class MethodClass {
public static void printSomething() {
System.out.println("Hello World");
}
}
The above is an example. MethodClass contains the method you want to run (such as your methodA(), methodB(), methodC(), and so forth. The doSameThing method takes in a Runnable, which is a functional interface that takes no parameters and returns no value. By passing the method printSomething, which takes no parameters and returns no value, we can run that method within the doSameThing method.
Of course, the type of functional interface you use would depend on what your methods are designed to accomplish.
Furthermore, if your other methods (methodA(), methodB(), ...) aren't used anywhere else in your code, you can implement the runnable interface in place with an anonymous class. Below is the previous example written in that form:
class A {
public static void main(String... args) {
new A().doSameThing(1, new Runnable() {
public void run() {
System.out.println("Hello World");
}
});
}
void doSameThing(int x, Runnable method) {
method.run();
}
}
Since Runnable is a functional interface, you could even go as far as using a lambda expression for this.
class A {
public static void main(String... args) {
new A().doSameThing(1, () -> {
System.out.println("Hello World");
});
}
void doSameThing(int x, Runnable method) {
method.run();
}
}
If you can use java 1.8 (and above), you can pass the method as a function
Function<Integer> method = (x) -> { //do something here }
And in doSameThing
doSameThing(int x, Function<Integer> fn) {
fn.apply(x)
}
I'm encountering problems understanding how function are passed to methods as parameters.
Searching on StackOverflow and StackExchange has brought me to a solution using java.util.Functions
public void someFunction(Functions <int[], int[]> myFunction);
(source: https://codereview.stackexchange.com/questions/186972/passing-a-generic-function-as-parameter)
Although this solution seems good to me, I'm facing problem when I need to pass a function which is intended to do nothing. For better understanding, consider the following example:
public class Example {
//do stuffs
myFunction(null);
}
public class Manager {
public void myFunction(Function<int[], void> funcToPass) { // Can't specify void as return value!
//do stuff
if(funcToPass != null) { // can't replicate such behaviour
funcToPass(someParams)
}
}
}
Can someone help me acquiring clear understanding on this topic? Thank you so much.
If you want to describe a function that does not return a value, you can use the Void type. This is a standard Java class, but is intended for use in this situation.
E.g.
Function<String, Void> stringPrinter = s -> {
System.out.println(s);
return null; // must return some value, null is acceptable since there is no Void instance
};
The return null; is important since, from the compiler's point of view, Void is just like any other class (e.g. String, Integer, etc). It doesn't know that it represents the absence of a value, whereas it does know that a function that returns void does not have a return value.
This means the compiler still expects some return statement in your code, just as if it were returning an Integer, and so you must return null;
EDIT:
You may find, however, if you are strictly dealing with functions with no returns, you are better suited to use a Consumer<T>. For example:
Consumer<String> stringPrinter = s -> System.out.println(s);
stringPrinter.accept("hello");
or, using a method reference:
Consumer<String> stringPrinter = System.out::println;
stringPrinter.accept("hello");
You can use Reflection API to pass a void method as a reference e.g.
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws Exception {
Class[] classParams = new Class[1];
classParams[0] = String.class;
Method method = Main.class.getMethod("hello", classParams);
Main obj = new Main();
System.out.println(new Main().getSum(obj, method, "world!", 10, 20));
}
public void hello(String msg) {
System.out.println("Hello " + msg);
}
int getSum(Object object, Method method, String msg, int x, int y) throws Exception {
Object[] objectParams = new Object[1];
objectParams[0] = msg;
method.invoke(object, objectParams);
return x + y;
}
}
Output:
Hello world!
30
In Java and Scala, how would I do the following:
I want to be able to pass a function into a function as a parameter where the function parameter is somewhat varying. For example, this is what I am locked into now in Java:
public void doSomething(Object object, Action1<Object> function) {
function.call(object);
}
public void doOtherThing(Object obj) {
System.out.println(obj);
}
doSomething("hello", this::doOtherThing);
This is what I want to be able to do:
public void doSomethingFancy(Object object, <Some Function Type Here> function) {
function.call(object);
}
public void doFancyThing(Object obj1, String str1, List list1) {
// do stuff
}
public void doFancyThing2(Object obj1, RandomObj rObj, Integer int1) {
// do stuff
}
...
doSomething("hello", this::doFancyThing);
doSomething("hello", this::doFancyThing2);
Basically I want the input function to have a variable type of input parameters. ActionN won't work because that would be passing a object array into my doFancyThing method and that obviously doesn't compile.
Any interface that has exactly one abstract method is a functional interface, and can thus be implemented using a lambda function or method reference.
#FunctionalInterface
public class MyFancyInterface {
void call(Object obj1, String str1, List list1);
}
How about,
An executor interface:
public interface Executor<T> {
void execute(T source);
}
A simple executor:
public class SimpleExecutor implements Executor<String> {
#Override
public void execute(String source) {
System.out.println(source);
}
}
A fancy executor:
public class FancyExecutor implements Executor<Object>{
#Override
public void execute(Object source) {
System.out.println("doing some fancy stuff");
}
}
An Action:
public class Action {
public <T> void doSomething(T source, Executor<T> executor) {
executor.execute(source);
}
}
And finally:
public static void main(String [] args) {
Action action = new Action();
action.doSomething("hey there", new SimpleExecutor());
action.doSomething(new Object(), new FancyExecutor());
}
With your definitions, doSomethingFancy("hello", this::doFancyThing); (I assume you wanted this instead of doSomething("hello", this::doFancyThing); in the second example) should call doFancyThing("hello"), which is impossible: it's missing two arguments! Similarly for doSomethingFancy("hello", this::doFancyThing2);, which calls doFancyThing2("hello").
And if you think about it a bit, you should find that changing the definition of doSomethingFancy will not help: there is just nothing it can do (except trivial things like returning null, object, function.hashCode(), etc.). So when the language doesn't let you even declare it, that's a good thing.
Two actual possibilities:
Provide missing arguments as part of the function:
public <T> void doSomething(T object, Action1<T> function) {
function.call(object);
}
doSomething("hello", x -> doFancyThing(x, "a", Collections.<Integer> emptyList()));
doSomething("hello", x -> doFancyThing2(x, some other arguments));
This works and it works great.
Use varargs to supply all parameters:
public void doSomething(Action1<Object[]> function, Object... args) {
function.call(object);
}
doSomething(args -> doFancyThing((Object) args(0), (String) args(1), (List) args(2)), "hello", "a", Collections.<Integer> emptyList()));
You could extract the args -> doFancyThing((Object) args(0), (String) args(1), (List) args(2)) part to a generic method, so the calls would look like
doSomething(toVarArgs(this::doFancyThing), "hello", "a", Collections.<Integer> emptyList()));
This is left as an exercise.
I would like to chain BiFunctions, like in the method chainWanted in the code sample below.
BiFunction takes Function as a parameter of AndThen. is it possible to somehow chain BiFunctions ?
The code here doesn't compile because of this and I cannot cast BiFunction to Function.
import java.util.function.BiFunction;
import java.util.function.Function;
import org.openqa.selenium.remote.RemoteWebDriver;
public class Wf {
BiFunction<RemoteWebDriver, WfParams, RemoteWebDriver> init = this::init;
BiFunction<RemoteWebDriver, WfParams, RemoteWebDriver> wait = this::wait;
BiFunction<RemoteWebDriver, WfParams, RemoteWebDriver> chainNow = init
.andThen(d -> {
System.out.println("--------------");
return null;
});
BiFunction<RemoteWebDriver, WfParams, RemoteWebDriver> chainWanted = init
.andThen((BiFunction) wait);
public RemoteWebDriver init(RemoteWebDriver d, WfParams params) {
System.out.println("init(d, params)");
return d;
}
public RemoteWebDriver wait(RemoteWebDriver d, WfParams params) {
System.out.println("Wf.wait(d, params)");
return d;
}
public static void main(String[] args) throws Exception {
new Wf().start();
}
private void start() {
chainNow.apply(null, null);
}
}
Chaining of one Function to another works naturally because the return value of the first function is passed as the argument to the next function, and that function's return value is passed as the argument to the subsequent function, and so forth. This doesn't work naturally with BiFunction because they take two arguments. The first argument would be the return value from the previous function, but what would the second argument be? It also explains why BiFunction allows chaining with andThen to a Function instead of to another BiFunction.
This suggests, however, that it would be possible to chain one BiFunction to another if there were some way of providing the value for second argument. This can be done by creating a helper function that stores the value for the second argument in a local variable. Then, a BiFunction can be converted into a Function by capturing that local variable from the environment and using it as the second argument.
Here's what that would look like.
BiFunction<RemoteWebDriver, WfParams, RemoteWebDriver> chainWanted = this::chainHelper;
RemoteWebDriver chainHelper(RemoteWebDriver driver, WfParams params) {
return
init.andThen(rwd -> wait.apply(rwd, params))
.apply(driver, params);
}
// ...
chainWanted.apply(driver, params);
The chainHelper method holds the params argument for later capture. We call init.andThen() in order to do the chaining. But this requires a Function whereas wait is a BiFunction. Instead of using a method reference this::wait we use the lambda expression
rwd -> wait.apply(rwd, params)
which captures params from the lexical environment. This gives a lambda expression that takes a single argument and returns a single value, so it's now a Function that wraps the wait which is a BiFunction. This is an example of partial application or currying. Finally, we call the resulting BiFunction using apply(), passing the original arguments.
Where should the WfParams come from for the invocation of wait? If you mean to reuse the same WfParams for all the functions calls, just put WfParams as a class member variable instead of passing it to each function.
class Wf {
private final WfParams params;
public Wf(WfParams params) {
this.params = params;
}
UnaryOperator<RemoteWebDriver> init = this::init;
UnaryOperator<RemoteWebDriver> wait = this::wait;
Function<RemoteWebDriver,RemoteWebDriver> chain = init.andThen(wait);
RemoteWebDriver init(RemoteWebDriver d) {
// can use WfParams here
return d;
}
RemoteWebDriver wait(RemoteWebDriver d) {
// can use WfParams here
return d;
}
private void start() {
chain.apply(null);
}
public static void main(String[] args) {
new Wf(new WfParams()).start();
}
}
Is there a particular reason you want to use function chaining like that? Why not simply call init(...); wait(...); from start()?
I did something like this - created my custom BiFunction.
The idea being:
Return type is same as the second argument
First argument is passed internally to chained biFunction
public interface BiFunctionCustom<T, U> extends BiFunction<T,U,U> {
default BiFunctionCustom<T, U> andThen(BiFunctionCustom<T, U> after) {
Objects.requireNonNull(after);
return (T t, U u) -> after.apply(t, apply(t, u));
}
}
I am looking for a way to pass a method by reference. I understand that Java does not pass methods as parameters, however, I would like to get an alternative.
I've been told interfaces are the alternative to passing methods as parameters but I don't understand how an interface can act as a method by reference. If I understand correctly an interface is simply an abstract set of methods that are not defined. I don't want to send an interface that needs to be defined every time because several different methods could call the same method with the same parameters.
What I would like to accomplish is something similar to this:
public void setAllComponents(Component[] myComponentArray, Method myMethod) {
for (Component leaf : myComponentArray) {
if (leaf instanceof Container) { //recursive call if Container
Container node = (Container) leaf;
setAllComponents(node.getComponents(), myMethod);
} //end if node
myMethod(leaf);
} //end looping through components
}
invoked such as:
setAllComponents(this.getComponents(), changeColor());
setAllComponents(this.getComponents(), changeSize());
Edit: as of Java 8, lambda expressions are a nice solution as other answers have pointed out. The answer below was written for Java 7 and earlier...
Take a look at the command pattern.
// NOTE: code not tested, but I believe this is valid java...
public class CommandExample
{
public interface Command
{
public void execute(Object data);
}
public class PrintCommand implements Command
{
public void execute(Object data)
{
System.out.println(data.toString());
}
}
public static void callCommand(Command command, Object data)
{
command.execute(data);
}
public static void main(String... args)
{
callCommand(new PrintCommand(), "hello world");
}
}
Edit: as Pete Kirkham points out, there's another way of doing this using a Visitor. The visitor approach is a little more involved - your nodes all need to be visitor-aware with an acceptVisitor() method - but if you need to traverse a more complex object graph then it's worth examining.
In Java 8, you can now pass a method more easily using Lambda Expressions and Method References. First, some background: a functional interface is an interface that has one and only one abstract method, although it can contain any number of default methods (new in Java 8) and static methods. A lambda expression can quickly implement the abstract method, without all the unnecessary syntax needed if you don't use a lambda expression.
Without lambda expressions:
obj.aMethod(new AFunctionalInterface() {
#Override
public boolean anotherMethod(int i)
{
return i == 982
}
});
With lambda expressions:
obj.aMethod(i -> i == 982);
Here is an excerpt from the Java tutorial on Lambda Expressions:
Syntax of Lambda Expressions
A lambda expression consists of the following:
A comma-separated list of formal parameters enclosed in parentheses. The CheckPerson.test method contains one parameter, p,
which represents an instance of the Person class.Note: You
can omit the data type of the parameters in a lambda expression. In
addition, you can omit the parentheses if there is only one parameter.
For example, the following lambda expression is also valid:
p -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
The arrow token, ->
A body, which consists of a single expression or a statement block. This example uses the following expression:
p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
If you specify a single expression, then the Java runtime evaluates the expression and then returns its value. Alternatively,
you can use a return statement:
p -> {
return p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25;
}
A return statement is not an expression; in a lambda expression, you must enclose statements in braces ({}). However, you do not have
to enclose a void method invocation in braces. For example, the
following is a valid lambda expression:
email -> System.out.println(email)
Note that a lambda expression looks a lot like a method declaration;
you can consider lambda expressions as anonymous methods—methods
without a name.
Here is how you can "pass a method" using a lambda expression:
interface I {
public void myMethod(Component component);
}
class A {
public void changeColor(Component component) {
// code here
}
public void changeSize(Component component) {
// code here
}
}
class B {
public void setAllComponents(Component[] myComponentArray, I myMethodsInterface) {
for(Component leaf : myComponentArray) {
if(leaf instanceof Container) { // recursive call if Container
Container node = (Container)leaf;
setAllComponents(node.getComponents(), myMethodInterface);
} // end if node
myMethodsInterface.myMethod(leaf);
} // end looping through components
}
}
class C {
A a = new A();
B b = new B();
public C() {
b.setAllComponents(this.getComponents(), component -> a.changeColor(component));
b.setAllComponents(this.getComponents(), component -> a.changeSize(component));
}
}
Class C can be shortened even a bit further by the use of method references like so:
class C {
A a = new A();
B b = new B();
public C() {
b.setAllComponents(this.getComponents(), a::changeColor);
b.setAllComponents(this.getComponents(), a::changeSize);
}
}
Since Java 8 there is a Function<T, R> interface (docs), which has method
R apply(T t);
You can use it to pass functions as parameters to other functions. T is the input type of the function, R is the return type.
In your example you need to pass a function that takes Component type as an input and returns nothing - Void. In this case Function<T, R> is not the best choice, since there is no autoboxing of Void type. The interface you are looking for is called Consumer<T> (docs) with method
void accept(T t);
It would look like this:
public void setAllComponents(Component[] myComponentArray, Consumer<Component> myMethod) {
for (Component leaf : myComponentArray) {
if (leaf instanceof Container) {
Container node = (Container) leaf;
setAllComponents(node.getComponents(), myMethod);
}
myMethod.accept(leaf);
}
}
And you would call it using method references:
setAllComponents(this.getComponents(), this::changeColor);
setAllComponents(this.getComponents(), this::changeSize);
Assuming that you have defined changeColor() and changeSize() methods in the same class.
If your method happens to accept more than one parameter, you can use BiFunction<T, U, R> - T and U being types of input parameters and R being return type. There is also BiConsumer<T, U> (two arguments, no return type). Unfortunately for 3 and more input parameters, you have to create an interface by yourself. For example:
public interface Function4<A, B, C, D, R> {
R apply(A a, B b, C c, D d);
}
Use the java.lang.reflect.Method object and call invoke
First define an Interface with the method you want to pass as a parameter
public interface Callable {
public void call(int param);
}
Implement a class with the method
class Test implements Callable {
public void call(int param) {
System.out.println( param );
}
}
// Invoke like that
Callable cmd = new Test();
This allows you to pass cmd as parameter and invoke the method call defined in the interface
public invoke( Callable callable ) {
callable.call( 5 );
}
While this is not yet valid for Java 7 and below, I believe that we should look to the future and at least recognize the changes to come in new versions such as Java 8.
Namely, this new version brings lambdas and method references to Java (along with new APIs, which are another valid solution to this problem. While they still require an interface no new objects are created, and extra classfiles need not pollute output directories due to different handling by the JVM.
Both flavors(lambda and method reference) require an interface available with a single method whose signature is used:
public interface NewVersionTest{
String returnAString(Object oIn, String str);
}
Names of methods will not matter from here on. Where a lambda is accepted, a method reference is as well. For example, to use our signature here:
public static void printOutput(NewVersionTest t, Object o, String s){
System.out.println(t.returnAString(o, s));
}
This is just a simple interface invocation, up until the lambda1 gets passed:
public static void main(String[] args){
printOutput( (Object oIn, String sIn) -> {
System.out.println("Lambda reached!");
return "lambda return";
}
);
}
This will output:
Lambda reached!
lambda return
Method references are similar. Given:
public class HelperClass{
public static String testOtherSig(Object o, String s){
return "real static method";
}
}
and main:
public static void main(String[] args){
printOutput(HelperClass::testOtherSig);
}
the output would be real static method. Method references can be static, instance, non-static with arbitrary instances, and even constructors. For the constructor something akin to ClassName::new would be used.
1 This is not considered a lambda by some, as it has side effects. It does illustrate, however, the use of one in a more straightforward-to-visualize fashion.
Last time I checked, Java is not capable of natively doing what you want; you have to use 'work-arounds' to get around such limitations. As far as I see it, interfaces ARE an alternative, but not a good alternative. Perhaps whoever told you that was meaning something like this:
public interface ComponentMethod {
public abstract void PerfromMethod(Container c);
}
public class ChangeColor implements ComponentMethod {
#Override
public void PerfromMethod(Container c) {
// do color change stuff
}
}
public class ChangeSize implements ComponentMethod {
#Override
public void PerfromMethod(Container c) {
// do color change stuff
}
}
public void setAllComponents(Component[] myComponentArray, ComponentMethod myMethod) {
for (Component leaf : myComponentArray) {
if (leaf instanceof Container) { //recursive call if Container
Container node = (Container) leaf;
setAllComponents(node.getComponents(), myMethod);
} //end if node
myMethod.PerfromMethod(leaf);
} //end looping through components
}
Which you'd then invoke with:
setAllComponents(this.getComponents(), new ChangeColor());
setAllComponents(this.getComponents(), new ChangeSize());
If you don't need these methods to return something, you could make them return Runnable objects.
private Runnable methodName (final int arg) {
return (new Runnable() {
public void run() {
// do stuff with arg
}
});
}
Then use it like:
private void otherMethodName (Runnable arg){
arg.run();
}
Java-8 onwards
Java 8 onwards, you can provide the implementation of the abstract method of a functional interface (an interface that has only one abstract method) using a lambda expression and pass the same to a method as a parameter.
#FunctionalInterface
interface ArithmeticFunction {
public int calcualate(int a, int b);
}
public class Main {
public static void main(String args[]) {
ArithmeticFunction addition = (a, b) -> a + b;
ArithmeticFunction subtraction = (a, b) -> a - b;
int a = 20, b = 5;
System.out.println(perform(addition, a, b));
// or
System.out.println(perform((x, y) -> x + y, a, b));
System.out.println(perform(subtraction, a, b));
// or
System.out.println(perform((x, y) -> x - y, a, b));
}
static int perform(ArithmeticFunction function, int a, int b) {
return function.calcualate(a, b);
}
}
Output:
25
25
15
15
ONLINE DEMO
Learn more about it from Method References.
I didn't find any example explicit enough for me on how to use java.util.function.Function for simple method as parameter function. Here is a simple example:
import java.util.function.Function;
public class Foo {
private Foo(String parameter) {
System.out.println("I'm a Foo " + parameter);
}
public static Foo method(final String parameter) {
return new Foo(parameter);
}
private static Function parametrisedMethod(Function<String, Foo> function) {
return function;
}
public static void main(String[] args) {
parametrisedMethod(Foo::method).apply("from a method");
}
}
Basically you have a Foo object with a default constructor. A method that will be called as a parameter from the parametrisedMethod which is of type Function<String, Foo>.
Function<String, Foo> means that the function takes a String as parameter and return a Foo.
The Foo::Method correspond to a lambda like x -> Foo.method(x);
parametrisedMethod(Foo::method) could be seen as x -> parametrisedMethod(Foo.method(x))
The .apply("from a method") is basically to do parametrisedMethod(Foo.method("from a method"))
Which will then return in the output:
>> I'm a Foo from a method
The example should be running as is, you can then try more complicated stuff from the above answers with different classes and interfaces.
Java do have a mechanism to pass name and call it. It is part of the reflection mechanism.
Your function should take additional parameter of class Method.
public void YouMethod(..... Method methodToCall, Object objWithAllMethodsToBeCalled)
{
...
Object retobj = methodToCall.invoke(objWithAllMethodsToBeCalled, arglist);
...
}
I did not found any solution here that show how to pass method with parameters bound to it as a parameter of a method. Bellow is example of how you can pass a method with parameter values already bound to it.
Step 1: Create two interfaces one with return type, another without. Java has similar interfaces but they are of little practical use because they do not support Exception throwing.
public interface Do {
void run() throws Exception;
}
public interface Return {
R run() throws Exception;
}
Example of how we use both interfaces to wrap method call in transaction. Note that we pass method with actual parameters.
//example - when passed method does not return any value
public void tx(final Do func) throws Exception {
connectionScope.beginTransaction();
try {
func.run();
connectionScope.commit();
} catch (Exception e) {
connectionScope.rollback();
throw e;
} finally {
connectionScope.close();
}
}
//Invoke code above by
tx(() -> api.delete(6));
Another example shows how to pass a method that actually returns something
public R tx(final Return func) throws Exception {
R r=null;
connectionScope.beginTransaction();
try {
r=func.run();
connectionScope.commit();
} catch (Exception e) {
connectionScope.rollback();
throw e;
} finally {
connectionScope.close();
}
return r;
}
//Invoke code above by
Object x= tx(() -> api.get(id));
Example of solution with reflection, passed method must be public
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
public class Program {
int i;
public static void main(String[] args) {
Program obj = new Program(); //some object
try {
Method method = obj.getClass().getMethod("target");
repeatMethod( 5, obj, method );
}
catch ( NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
System.out.println( e );
}
}
static void repeatMethod (int times, Object object, Method method)
throws IllegalAccessException, InvocationTargetException {
for (int i=0; i<times; i++)
method.invoke(object);
}
public void target() { //public is necessary
System.out.println("target(): "+ ++i);
}
}
Use the Observer pattern (sometimes also called Listener pattern):
interface ComponentDelegate {
void doSomething(Component component);
}
public void setAllComponents(Component[] myComponentArray, ComponentDelegate delegate) {
// ...
delegate.doSomething(leaf);
}
setAllComponents(this.getComponents(), new ComponentDelegate() {
void doSomething(Component component) {
changeColor(component); // or do directly what you want
}
});
new ComponentDelegate()... declares an anonymous type implementing the interface.
Here is a basic example:
public class TestMethodPassing
{
private static void println()
{
System.out.println("Do println");
}
private static void print()
{
System.out.print("Do print");
}
private static void performTask(BasicFunctionalInterface functionalInterface)
{
functionalInterface.performTask();
}
#FunctionalInterface
interface BasicFunctionalInterface
{
void performTask();
}
public static void main(String[] arguments)
{
performTask(TestMethodPassing::println);
performTask(TestMethodPassing::print);
}
}
Output:
Do println
Do print
I'm not a java expert but I solve your problem like this:
#FunctionalInterface
public interface AutoCompleteCallable<T> {
String call(T model) throws Exception;
}
I define the parameter in my special Interface
public <T> void initialize(List<T> entries, AutoCompleteCallable getSearchText) {.......
//call here
String value = getSearchText.call(item);
...
}
Finally, I implement getSearchText method while calling initialize method.
initialize(getMessageContactModelList(), new AutoCompleteCallable() {
#Override
public String call(Object model) throws Exception {
return "custom string" + ((xxxModel)model.getTitle());
}
})
I appreciate the answers above but I was able to achieve the same behavior using the method below; an idea borrowed from Javascript callbacks. I'm open to correction though so far so good (in production).
The idea is to use the return type of the function in the signature, meaning that the yield has to be static.
Below is a function that runs a process with a timeout.
public static void timeoutFunction(String fnReturnVal) {
Object p = null; // whatever object you need here
String threadSleeptime = null;
Config config;
try {
config = ConfigReader.getConfigProperties();
threadSleeptime = config.getThreadSleepTime();
} catch (Exception e) {
log.error(e);
log.error("");
log.error("Defaulting thread sleep time to 105000 miliseconds.");
log.error("");
threadSleeptime = "100000";
}
ExecutorService executor = Executors.newCachedThreadPool();
Callable<Object> task = new Callable<Object>() {
public Object call() {
// Do job here using --- fnReturnVal --- and return appropriate value
return null;
}
};
Future<Object> future = executor.submit(task);
try {
p = future.get(Integer.parseInt(threadSleeptime), TimeUnit.MILLISECONDS);
} catch (Exception e) {
log.error(e + ". The function timed out after [" + threadSleeptime
+ "] miliseconds before a response was received.");
} finally {
// if task has started then don't stop it
future.cancel(false);
}
}
private static String returnString() {
return "hello";
}
public static void main(String[] args) {
timeoutFunction(returnString());
}