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.
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.
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.
How to find all the classes which implement a given interface?
A working code-sample:
var instances = from t in Assembly.GetExecutingAssembly().GetTypes()
where t.GetInterfaces().Contains(typeof(ISomething))
&& t.GetConstructor(Type.EmptyTypes) != null
select Activator.CreateInstance(t) as ISomething;
foreach (var instance in instances)
{
instance.Foo(); // where Foo is a method of ISomething
}
Edit Added a check for a parameterless constructor so that the call to CreateInstance will succeed.
Get all classes that implement an interface and call a function in .NET Core
Since it's always null I think that the problem is that you're not creating an instance of your handler. I prepared a demo for you where I did that and it works.
public interface ICommandHandler
{
string Command { get; }
Task ExecuteAsync();
}
public class FirstCommandHandler : ICommandHandler
{
public string Command => "First";
public async Task ExecuteAsync()
{
Console.WriteLine("Hello from first.");
await Task.Delay(10);
}
}
public class SecondCommandHandler : ICommandHandler
{
public string Command => "Second";
public async Task ExecuteAsync()
{
Console.WriteLine("Hello from second.");
await Task.Delay(10);
}
}
public class Program
{
static async Task Main(string[] args)
{
var handlers = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => typeof(ICommandHandler).IsAssignableFrom(p) && p.IsClass);
foreach (var handler in handlers)
{
var handlerInstance = (ICommandHandler)Activator.CreateInstance(handler);
if (handlerInstance.Command == "First")
{
await handlerInstance.ExecuteAsync();
}
}
}
}
If it's not the case, could you show some more code? Are you trying to check Command
value by reflection?
C# Iterate through all classes implementing interface
So i got the solution with the help of @StevenWiliams and @JimWolff
For anyone who for some reason has the same problem, here is my udated code:
IEnumerable<Type> _commands = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).Where(t => t.GetInterfaces().Contains(typeof(ICommand)));
foreach (Type _type in _commands)
{
ICommand _command = (ICommand)Activator.CreateInstance(_type);
Debug.Log("Name: " + _command.name);
}
The problem I faced was, that I forgot, that classes can have multiple instances and therefor i cant get the value of the class directly. Creating an instance fixes this problem.
Again, credits to @StevenWiliams and @JimWolff.
How to find which classes implement a particular interface in Eclipse?
Right-click on the interface, and choose "Open type hierarchy". Then click on "Show the subtype hierarchy".
How can I find all implementations of interface in classpath?
At best, this will be expensive. At worst (depending on the classloaders) it may be impossible.
I strongly suggest that you look for an alternative approach to the underlying problem that you are trying to address.
Related Topics
Convert Datetime to Date Format Dd/Mm/Yyyy
Split String into String Array of Single Characters
Iis Server & ASP.NET Core - 500.19 with Error Code 0X8007000D on Httpplatformhandler Tag
Nullable Reference Types: How to Specify "T" Type Without Constraining to Class or Struct
How to Prevent Flickering in Listview When Updating a Single Listviewitem's Text
Accordion in Windows Forms Datagridview
Badimageformatexception When Loading 32 Bit Dll, Target Is X86
Ef Code First - How to Set Identity Seed
Convert from Scientific Notation String to Float in C#
A Timeout Occured After 30000Ms Selecting a Server Using Compositeserverselector
Wait Some Seconds Without Blocking UI Execution
How to Programmatically Generate an X509 Certificate Using Only C#
How to Get Ip of All Hosts in Lan
Send Keys Through Sendinput in User32.Dll
What's a Good Threadsafe Singleton Generic Template Pattern in C#
What Is a Good Unique Pc Identifier