How to Find All Implementations of an Interface

Getting all types that implement an interface

Mine would be this in c# 3.0 :)

var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));

Basically, the least amount of iterations will always be:

loop assemblies  
loop types
see if implemented.

How do you find all implementations of an interface?

(Edit based on comment...)

If you have ReSharper installed:

In Visual Studio, right click on the type name and choose "Go to Inheritor". Alternatively, select the type name, then go to ReSharper/View/Type Hierarchy to open up a new tab. (The menu will show you the keyboard shortcut - this can vary, which is why I explained how to find it :)

If you don't have ReSharper:

  • You can use Reflector, which is able to show you all the type hierarchy very easily - just under the type name are expandable items for base types and derived types. Similar tools are available such as ILSpy and dotPeek.
  • Buy ReSharper - it's a great tool :)

Typescript - Get all implementations of interface

As I mentioned in the comments, it's a stated non-goal of TypeScript (see non-goal #5) to emit JavaScript that is dependent on the type system, so there will be nothing at runtime you can use automatically to do what you want.

You can, of course, use TypeScript to help you maintain a registry of types that can be used almost exactly how you want. I'd suggest using class decorators, like so:

interface IControlPanel {
// add some methods or something to distinguish from {}
doAThing(): void;
}

// add a registry of the type you expect
namespace IControlPanel {
type Constructor<T> = {
new(...args: any[]): T;
readonly prototype: T;
}
const implementations: Constructor<IControlPanel>[] = [];
export function GetImplementations(): Constructor<IControlPanel>[] {
return implementations;
}
export function register<T extends Constructor<IControlPanel>>(ctor: T) {
implementations.push(ctor);
return ctor;
}
}

Now, instead of declaring that the class implements IControlPanel, you use @IControlPanel.register:

@IControlPanel.register
class BasicControlPanel {
doAThing() { }
}

@IControlPanel.register
class AdvancedControlPanel {
doAThing() { }
}

If you try to register a class that does not implement IControlPanel, you will get an error:

// error, doAThing is missing from BadControlPanel
@IControlPanel.register
class BadControlPanel {
doNothing() { }
}

Now you can use the registry the way you want, mostly:

window.onload = () => {
var controlPanels = IControlPanel.GetImplementations();
for (var x = 0; x < controlPanels.length; x++) {
document.write(controlPanels[x].name + ", ");
const panel = new controlPanels[x]();
panel.doAThing();
}
};

I say "mostly" because I've stored constructors, not strings, since you wanted a way to instantiate them. You can get the name property of the constructor for the string. And you can instantiate the classes, assuming they all take the same constructor argument types.

Hope that helps; good luck!

Stackblitz example

How to find all implementations of an interface with Roslyn?

Call SymbolFinder.FindImplementationsAsync(interfaceSymbol, solution).

Source

Finding all classes implementing a specific interface

I had a similar need where I wanted to make sure that any classes created that implemented a certain interface were always truly serializable. I created a JavaClassFinder which walks through all directories in the classpath, and finds all classes assignable to the interface I cared about. Here is a code snippet:

public <T> List<Class<? extends T>> findAllMatchingTypes(Class<T> toFind) {
foundClasses = new ArrayList<Class<?>>();
List<Class<? extends T>> returnedClasses = new ArrayList<Class<? extends T>>();
this.toFind = toFind;
walkClassPath();
for (Class<?> clazz : foundClasses) {
returnedClasses.add((Class<? extends T>) clazz);
}
return returnedClasses;
}

I'm happy to share the code with you if it helps. The only draw back is that this will only handle .class files -- I didn't add the feature to unzip .jars and read class files from there. (But it wouldn't be a huge project to add that.)

UPDATE: I checked my source code for the above, and found it depends on a lot of helper classes in our standard utility library. To make it easier, I zipped up all the code needed, which you can download from JavaClassFinder.zip. This will set up directly in Eclipse, and you can take whatever portions of the code you need.

You will find a JUnit3 test in the project, called JavaClassFinderTest.java, which shows you the features and usage of the JavaClassFinder class. The only external dependency needed to run the Junit test is Junit.

Basic usage of this utility:

    JavaClassFinder classFinder = new JavaClassFinder();
List<Class<? extends MyTagInterface>> classes = classFinder.findAllMatchingTypes(MyTagInterface.class);

This will give you a List which contains any classes in the classpath which are assignable from the "MyTagInterface.class" (for example). Hope this helps.

Get all implementations types of a generic interface

You can try working example.

Declarations:

public interface IEntity { }
public class Entity1 : IEntity { }
public class Entity2 : IEntity { }

public interface IEntityModelBuilder<out T> where T : IEntity { }

public class BaseClass1 : IEntityModelBuilder<Entity1>
{
public BaseClass1(int a) { }
}
public class BaseClass2 : IEntityModelBuilder<Entity2>
{
public BaseClass2(int a) { }
}

Usage:

List<IEntityModelBuilder<IEntity>> objects = Assembly.GetExecutingAssembly().GetTypes()
.Where(x => x.GetInterfaces().Any(y => y.IsGenericType && && y.Name == "IEntityModelBuilder`1"))
.Select(x => (IEntityModelBuilder<IEntity>)Activator.CreateInstance(x, new object[] { 0 })).ToList();

Find Java classes implementing an interface

Awhile ago, I put together a package for doing what you want, and more. (I needed it for a utility I was writing). It uses the ASM library. You can use reflection, but ASM turned out to perform better.

I put my package in an open source library I have on my web site. The library is here: http://software.clapper.org/javautil/. You want to start with the with ClassFinder class.

The utility I wrote it for is an RSS reader that I still use every day, so the code does tend to get exercised. I use ClassFinder to support a plug-in API in the RSS reader; on startup, it looks in a couple directory trees for jars and class files containing classes that implement a certain interface. It's a lot faster than you might expect.

The library is BSD-licensed, so you can safely bundle it with your code. Source is available.

If that's useful to you, help yourself.

Update: If you're using Scala, you might find this library to be more Scala-friendly.



Related Topics



Leave a reply



Submit