Passing a void method using Callable using Java generics and Java 8 lambda

I am trying to write a general performance logging function in which I can pass any method that needs to be included and it will write the runtime to my database. This works for me in most cases, but I get compiler errors when passing a method that returns void:

no instance(s) of type variable(s) T exist so that void conforms to T

Here is my class:

public class Performance {
    public static <T> T measureExecTime(Callable<T> c, String gid, String name) {
        T call = null;
        try {
            if (Constants.DEBUG) {
                Calendar start = Calendar.getInstance();
                call = c.call();
                Calendar end = Calendar.getInstance();
                long diff = end.getTimeInMillis() - start.getTimeInMillis();
                // log diff to database
            } else {
                call = c.call();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return call;
    }
}

And here is what I call him:

Performance.measureExecTime(() -> myMethod(myMethodParam1, myMethodParam2), "gid", "database_qualifier");

Is it possible for this functionality to behave according to void methods, or am I out of luck?

+4
source share
2 answers

Callable . null, lambda:

Performance.measureExecTime(() -> {
    myMethod(myMethodParam1, myMethodParam2);
    return null;
}, "gid", "database_qualifier");

, , :

static Callable<?> wrap(Runnable r) {
    return () -> {
        r.run();
        return null;
    };
}
// ...
Performance.measureExecTime(wrap(() -> myMethod(myMethodParam1, myMethodParam2)), "gid", "database_qualifier");
+7

.

void : .

, !

0

Source: https://habr.com/ru/post/1653479/


All Articles