[java] Test if object implements interface

This has probably been asked before, but a quick search only brought up the same question asked for C#. See here.

What I basically want to do is to check wether a given object implements a given interface.

I kind of figured out a solution but this is just not comfortable enough to use it frequently in if or case statements and I was wondering wether Java does not have built-in solution.

public static Boolean implementsInterface(Object object, Class interf){
    for (Class c : object.getClass().getInterfaces()) {
        if (c.equals(interf)) {
            return true;
        }
    }
    return false;
}


EDIT: Ok, thanks for your answers. Especially to Damien Pollet and Noldorin, you made me rethink my design so I don't test for interfaces anymore.

This question is related to java

The answer is


that was easy :

   interf.isInstance(object)

For the instance:

if (obj is IMyInterface) {}

For the class:

Check if typeof(MyClass).GetInterfaces() contains the interface.


What worked for me is:

Assert.IsNotNull(typeof (YourClass).GetInterfaces().SingleOrDefault(i => i == typeof (ISomeInterface)));


I had this problem tonight with android and after looking at the javadoc solutions I came up with this real working solution just for people like me that need a little more than a javadoc explanation.

Here's a working example with an actual interface using android java. It checks the activity that called implemented the AboutDialogListener interface before attempting to cast the AboutDialogListener field.

public class About extends DialogFragment implements OnClickListener,
    OnCheckedChangeListener {

public static final String FIRST_RUN_ABOUT = "com.gosylvester.bestrides.firstrunabout";


public interface AboutDialogListener {
    void onFinishEditDialog(Boolean _Checked);
}

private AboutDialogListener adl;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    Activity a = this.getActivity();
    if (AboutDialogListener.class.isInstance(a)) {
        adl = (AboutDialogListener) a;
        }
}

... Later I check if the field adl is !null before calling the interface

@Override
public void onStop() {
    super.onStop();
    sharedPref.edit().putBoolean(About.FIRST_RUN_ABOUT, _Checked).commit();
    // if there is an interface call it.
    if (adl != null) {
        adl.onFinishEditDialog(is_Checked());
    }
}

if (object is IBlah)

or

IBlah myTest = originalObject as IBlah

if (myTest != null)

Using the is or as operators is the correct way if you know the interface type at compile time and have an instance of the type you are testing. Something that no one else seems to have mentioned is Type.IsAssignableFrom:

if( typeof(IMyInterface).IsAssignableFrom(someOtherType) )
{
}

I think this is much neater than looking through the array returned by GetInterfaces and has the advantage of working for classes as well.


In addition to testing using the "is" operator, you can decorate your methods to make sure that variables passed to it implement a particular interface, like so:

public static void BubbleSort<T>(ref IList<T> unsorted_list) where T : IComparable
{
     //Some bubbly sorting
}

I'm not sure which version of .Net this was implemented in so it may not work in your version.


I used

Assert.IsTrue(myObject is ImyInterface);

for a test in my unit test which tests that myObject is an object which has implemented my interface ImyInterface.


A variation on @AndrewKennan's answer I ended up using recently for types obtained at runtime:

if (serviceType.IsInstanceOfType(service))
{
    // 'service' does implement the 'serviceType' type
}

If you want to use the typecasted object after the check:
Since C# 7.0:

if (obj is IMyInterface myObj)

This is the same as

IMyInterface myObj = obj as IMyInterface;
if (myObj != null)

See .NET Docs: Pattern matching with is # Type pattern


Using the is or as operators is the correct way if you know the interface type at compile time and have an instance of the type you are testing. Something that no one else seems to have mentioned is Type.IsAssignableFrom:

if( typeof(IMyInterface).IsAssignableFrom(someOtherType) )
{
}

I think this is much neater than looking through the array returned by GetInterfaces and has the advantage of working for classes as well.


Recently I tried using Andrew Kennan's answer and it didn't work for me for some reason. I used this instead and it worked (note: writing the namespace might be required).

if (typeof(someObject).GetInterface("MyNamespace.IMyInterface") != null)

This should work :

MyInstace.GetType().GetInterfaces();

But nice too :

if (obj is IMyInterface)

Or even (not very elegant) :

if (obj.GetType() == typeof(IMyInterface))

This should do:

public static boolean implementsInterface(Object object, Class interf){
    return interf.isInstance(object);
}

For example,

 java.io.Serializable.class.isInstance("a test string")

evaluates to true.


What worked for me is:

Assert.IsNotNull(typeof (YourClass).GetInterfaces().SingleOrDefault(i => i == typeof (ISomeInterface)));


In addition to testing using the "is" operator, you can decorate your methods to make sure that variables passed to it implement a particular interface, like so:

public static void BubbleSort<T>(ref IList<T> unsorted_list) where T : IComparable
{
     //Some bubbly sorting
}

I'm not sure which version of .Net this was implemented in so it may not work in your version.


Using the is or as operators is the correct way if you know the interface type at compile time and have an instance of the type you are testing. Something that no one else seems to have mentioned is Type.IsAssignableFrom:

if( typeof(IMyInterface).IsAssignableFrom(someOtherType) )
{
}

I think this is much neater than looking through the array returned by GetInterfaces and has the advantage of working for classes as well.


If you want to test for interfaces:

public List<myType> getElement(Class<?> clazz) {
    List<myType> els = new ArrayList<myType>();
    for (myType e: this.elements.values()) {
        if (clazz.isAssignableFrom(e.getClass())) {
            els.add(e);
        }
    }
    return els;

}

clazz is an Interface and myType is a Type that you defined that may implement a number of interfaces. With this code you get only the types that implement a defined interface


In addition to testing using the "is" operator, you can decorate your methods to make sure that variables passed to it implement a particular interface, like so:

public static void BubbleSort<T>(ref IList<T> unsorted_list) where T : IComparable
{
     //Some bubbly sorting
}

I'm not sure which version of .Net this was implemented in so it may not work in your version.


This should work :

MyInstace.GetType().GetInterfaces();

But nice too :

if (obj is IMyInterface)

Or even (not very elegant) :

if (obj.GetType() == typeof(IMyInterface))

With Apache commons-lang ArrayUtils, see if the interface you require is contained in the interfaces of you object

public static Boolean implementsInterface(Object object, Class interf){
    return ArrayUtils.contains(object.getClass().getInterfaces(), interf);
}

For the instance:

if (obj is IMyInterface) {}

For the class:

Check if typeof(MyClass).GetInterfaces() contains the interface.


This should work :

MyInstace.GetType().GetInterfaces();

But nice too :

if (obj is IMyInterface)

Or even (not very elegant) :

if (obj.GetType() == typeof(IMyInterface))

I used

Assert.IsTrue(myObject is ImyInterface);

for a test in my unit test which tests that myObject is an object which has implemented my interface ImyInterface.


For the instance:

if (obj is IMyInterface) {}

For the class:

Check if typeof(MyClass).GetInterfaces() contains the interface.


In addition to testing using the "is" operator, you can decorate your methods to make sure that variables passed to it implement a particular interface, like so:

public static void BubbleSort<T>(ref IList<T> unsorted_list) where T : IComparable
{
     //Some bubbly sorting
}

I'm not sure which version of .Net this was implemented in so it may not work in your version.


For the instance:

if (obj is IMyInterface) {}

For the class:

Check if typeof(MyClass).GetInterfaces() contains the interface.


if (object is IBlah)

or

IBlah myTest = originalObject as IBlah

if (myTest != null)

if (object is IBlah)

or

IBlah myTest = originalObject as IBlah

if (myTest != null)

This Post is a good answer.

public interface IMyInterface {}

public class MyType : IMyInterface {}

This is a simple sample:

typeof(IMyInterface).IsAssignableFrom(typeof(MyType))

or

typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))

A variation on @AndrewKennan's answer I ended up using recently for types obtained at runtime:

if (serviceType.IsInstanceOfType(service))
{
    // 'service' does implement the 'serviceType' type
}

Recently I tried using Andrew Kennan's answer and it didn't work for me for some reason. I used this instead and it worked (note: writing the namespace might be required).

if (typeof(someObject).GetInterface("MyNamespace.IMyInterface") != null)

I had a situation where I was passing a variable to a method and wasn't sure if it was going to be an interface or an object.

The goals were:

  1. If item is an interface, instantiate an object based on that interface with the interface being a parameter in the constructor call.
  2. If the item is an object, return a null since the constuctor for my calls are expecting an interface and I didn't want the code to tank.

I achieved this with the following:

    if(!typeof(T).IsClass)
    {
       // If your constructor needs arguments...
       object[] args = new object[] { my_constructor_param };
       return (T)Activator.CreateInstance(typeof(T), args, null);
    }
    else
       return default(T);

Using the is or as operators is the correct way if you know the interface type at compile time and have an instance of the type you are testing. Something that no one else seems to have mentioned is Type.IsAssignableFrom:

if( typeof(IMyInterface).IsAssignableFrom(someOtherType) )
{
}

I think this is much neater than looking through the array returned by GetInterfaces and has the advantage of working for classes as well.


if (object is IBlah)

or

IBlah myTest = originalObject as IBlah

if (myTest != null)

I had a situation where I was passing a variable to a method and wasn't sure if it was going to be an interface or an object.

The goals were:

  1. If item is an interface, instantiate an object based on that interface with the interface being a parameter in the constructor call.
  2. If the item is an object, return a null since the constuctor for my calls are expecting an interface and I didn't want the code to tank.

I achieved this with the following:

    if(!typeof(T).IsClass)
    {
       // If your constructor needs arguments...
       object[] args = new object[] { my_constructor_param };
       return (T)Activator.CreateInstance(typeof(T), args, null);
    }
    else
       return default(T);

I prefer instanceof:

if (obj instanceof SomeType) { ... }

which is much more common and readable than SomeType.isInstance(obj)


This should work :

MyInstace.GetType().GetInterfaces();

But nice too :

if (obj is IMyInterface)

Or even (not very elegant) :

if (obj.GetType() == typeof(IMyInterface))

If you want to use the typecasted object after the check:
Since C# 7.0:

if (obj is IMyInterface myObj)

This is the same as

IMyInterface myObj = obj as IMyInterface;
if (myObj != null)

See .NET Docs: Pattern matching with is # Type pattern


This Post is a good answer.

public interface IMyInterface {}

public class MyType : IMyInterface {}

This is a simple sample:

typeof(IMyInterface).IsAssignableFrom(typeof(MyType))

or

typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))