Test If Object Implements Interface

Test if object implements interface

if (object is IBlah)

or

IBlah myTest = originalObject as IBlah

if (myTest != null)

Test if object implements interface

The instanceof operator does the work in a NullPointerException safe way. For example:

 if ("" instanceof java.io.Serializable) {
// it's true
}

yields true. Since:

 if (null instanceof AnyType) {
// never reached
}

yields false, the instanceof operator is null safe (the code you posted isn't).

instanceof is the built-in, compile-time safe alternative to Class#isInstance(Object)

How to check if an object implements an interface?

For an instance

Character.Gorgon gor = new Character.Gorgon();

Then do

gor instanceof Monster

For a Class instance do

Class<?> clazz = Character.Gorgon.class;
Monster.class.isAssignableFrom(clazz);

Test if an object implements an interface

Use TypeOf...Is:

If TypeOf objectParameter Is ISpecifiedInterface Then
'do stuff
End If

How to determine if a type implements an interface with C# reflection

You have a few choices:

  1. typeof(IMyInterface).IsAssignableFrom(typeof(MyType))
  2. typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))
  3. With C# 6 you can use typeof(MyType).GetInterface(nameof(IMyInterface)) != null

For a generic interface, it’s a bit different.

typeof(MyType).GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMyInterface<>))

Checking if an instance's class implements an interface?

interface IInterface
{
}

class TheClass implements IInterface
{
}

$cls = new TheClass();
if ($cls instanceof IInterface) {
echo "yes";
}

You can use the "instanceof" operator. To use it, the left operand is a class instance and the right operand is an interface. It returns true if the object implements a particular interface.

Check if 'T' inherits or implements a class/interface

There is a Method called Type.IsAssignableFrom().

To check if T inherits/implements Employee:

typeof(Employee).IsAssignableFrom(typeof(T));

If you are targeting .NET Core, the method has moved to TypeInfo:

typeof(Employee).GetTypeInfo().IsAssignableFrom(typeof(T).Ge‌​tTypeInfo())

Note that if you want to constrain your type T to implement some interface or inherit from some class, you should go for @snajahi's answer, which uses compile-time checks for that and genereally resembles a better approach to this problem.

Check if an object implements an interface at runtime with TypeScript

No.

Currently, types are used only during development and compile time.
The type information is not translated in any way to the compiled
JavaScript code.

From https://stackoverflow.com/a/16016688/318557, as pointed out by @JasonEvans

There is an open issue since Jun 2015 about this in the TypeScript repo: https://github.com/microsoft/TypeScript/issues/3628



Related Topics



Leave a reply



Submit