javadynamicimplements

How to pass an interface to a method


I am trying to create a function which takes two parameters - a class instance and a interface - then returns true if the provided class instance implements the provided interface. My problem is that I cannot find a way to pass a interface as a parameter in this way.

My attempt currently looks something like this:

interface myInterface
{
}

class myClass implements myInterface
{
}

...

// Function to check if a class implements an interface:
boolean doesImplementInterface(object classToTest, ??? interfaceToTestAgainst)
{
    if(i.getClass().isInterface())
    {
        return o.getClass().isInstance(i);
    }
    return false;
}

...

// Would call the "doesImplementInterface" method like this:
doesImplementInterface(new myClass(), myInterface);

It might be hard to see here, but when defining the "doesImplementInterface" function, I cannot figure out what type the second parameter must be. I am attempting to pass the interface that the provided class will be tested against, but as far as I can find, there is no variable type that I could use to pass a interface in this way.

Is passing a interface as a parameter in this way possible, or should I begin exploring alternative options?


Solution

  • Explanation

    You need to pass the interface as Class (documentation) token. Also, you need to check the opposite way: interfaceToTestAgainst.isInstance(classToTest). Currently, you are trying to check whether the interface would be an instance of the class.

    boolean doesImplementInterface(Object classToTest, Class<?> interfaceToTestAgainst) {
        if (!interfaceToTestAgainst.isInterface()) {
            return false;
        }
        return interfaceToTestAgainst.isInstance(classToTest);
    }
    

    or in one line:

    boolean doesImplementInterface(Object classToTest, Class<?> interfaceToTestAgainst) {
        return interfaceToTestAgainst.isInterface()
            && interfaceToTestAgainst.isInstance(classToTest);
    }
    

    Changed the naming a bit:

    boolean isInstanceOfInterface(Object obj, Class<?> interfaceToken) {
        return interfaceToken.isInterface()
            && interfaceToken.isInstance(obj);
    }
    

    A call of that method:

    boolean result = isInstanceOfInterface(new Dog(), CanBark.class);
    

    Note

    Your question sounds like a XY problem. There might be way better solutions to solve what you are trying to solve with this attempt in the first place.

    Losing type information, degrading the system to one which is not compile-time-safe anymore is generally very bad, if it can be avoided.

    Consider re-thinking/-designing your approach. Just a note though, I do not know what you want to solve with that in the first place.