Is it possible to compare two empty Runnable for equality?

I have a method which returns a Runnable. In certain situations, it will return an empty runnable (() -> {}) and I would like to test that these situations are well respected.

Hence, I was thinking to do some simple unit tests such as:

private static final Runnable EMPTY = () -> {};

public void test() {
    Runnable action = myObject.myMethod(myParameters);
    assertEquals(EMPTY, action);

The above clearly doesn’t work since Runnable is a functional interface, and I guess that would be up to me to override the equals method eventually or else I will just call the one of the superclass Object and hence I would fail my assertion.

On one hand, I understand it’s hard (or simply impossible?) to test equality of two runnables which may potentially contain anything. On the other hand, I would really like to test just if the runnable is empty, nothing else.

So for now, I have created a public static final Runnable EMPTY on the myObject class which I return when I need:

public class MyObject {
    public static final Runnable EMPTY = () -> {};
    public Runnable myMethod(MyParameters myParameters) {
        if (something) {
            return EMPTY;
        if (somethingElse) {
            return EMPTY;
        return anotherRunnable;

and then I reference this instance from the tests, which works fine for a limited number of tests:

assertEquals(MyObject.EMPTY, action);

But the Runnable may one day also be provided from the external, which means I would have no control on the fact that the empty runnable is exactly my static empty instance, and in this case I would really need to know whether the provided runnable is empty or not.

Any idea? Am I asking for something impossible?


Short answer: it is impossible.

Long answer: It is possible, but you don’t want to do it because you have to disassembly class file for said Runnable and check method body. Which is too much effort. There should be easier way to achieve result you want.