开发者

How can I find all implementations of interface in classpath?

开发者 https://www.devze.com 2023-01-04 16:13 出处:网络
I\'m implementing an interface and now I开发者_高级运维\'d like to get all implementations of this interface in classpath. Is this possible or should I do something else?The Reflections library will l

I'm implementing an interface and now I开发者_高级运维'd like to get all implementations of this interface in classpath. Is this possible or should I do something else?


The Reflections library will let you do that (to an extent):

Set<Class<? extends SomeClassOrInterface>> subTypes = 
     reflections.getSubTypesOf(SomeClassOrInterface.class);

However I wouldn't recommend that. Imagine a typical classpath with 50 external jars, each of which being a big framework like spring, hibernate, aspectj, jsf, etc. It would take much time.

If you want to have some kind of plugin mechanism, so that others can implement your interfaces and supply jars with the implementation, then look at java.util.ServiceLoader


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号