Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if a class is capable of implementing an interface at runtime in Java (JDK 17)

I need to determine whether a class is capable of implementing an interface when it does not explicitly implement that interface. I would like to determine this at runtime, I am using reflections to gather classes.

For example:

Lets say I have the following class:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class Clazz {
    public void doSomething() {
        // ... do it
    }
}

And the following interface:

public interface ClazzInterface {
    public void doSomething();
}

Clazz does not implement ClazzInterface, however it is compatible with ClazzInterface and could implement it without any modification. I am looking for a way to check this at runtime.

Something like:

boolean canImplement = Clazz.class canImplement ClazzInterface.class

Is this possible either through a built in library or method or some logic I could write myself?

I have tried using reflections isAssignableFrom and this does not work, returning false for the above example.

>Solution :

There is no such concept of "is capable of implementing" an interface. A class either does (or does not) implement an interface. However, you can use reflection to dynamically call some method. It has caveats and limitations (of course). For example, it’s usually slow. But here is a doSomething with "duck-typing".

public static final void doSomething(Object o) {
    if (o == null) {
        return;
    }
    Class<?> cls = o.getClass();
    try {
        Method m = cls.getMethod("doSomething", new Class<?>[] {});
        if (m != null) {
            m.invoke(o, new Object[] {});
        }
    } catch (final Exception e) {
        e.printStackTrace();
    }
}

Note the line if (m != null), that does check if doSomething is available in the actual instance o. You could test for the presence of all necessary methods in the same manner.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading