dynamically load implementation of interface in Java

可紊 提交于 2019-12-08 12:37:05

问题


I'm looking for functionality in Java similar to the .NET Managed Extensibility Framework (http://mef.codeplex.com/). For those who don't know MEF, I want something like this:

Given an interface

public interface IFoo {
 ...
}    

Dynamically load an implementation of an interface by looking in loaded jars.

IFoo foo = loadClassThatImplementsInterface<IFoo>();

The point is that the programmer does not know the name of the implementation at code time, but provides in code an extentsion point.

Is this not possible in Java at all? I found some Google hits stating that it is not possible, but this seems a bit... eh?

There are plenty of examples of using a class loader when the fully qualified name of the implementation is know at compile time. That is not what I want.


回答1:


In 'pure' Java you can use ServiceLoader: http://download.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html

You simply provide meta-data in your extension jar, that's smart and extensible easily.

Or look for a DI framework like Guice or Spring...




回答2:


It's quite possible, with a loadClassThatImplementsInterface(IFoo.class).



来源:https://stackoverflow.com/questions/3957637/dynamically-load-implementation-of-interface-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!