动态加载Java接口的实现 [英] dynamically load implementation of interface in Java

查看:252
本文介绍了动态加载Java接口的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找Java中与.NET托管扩展框架(http://mef.codeplex.com/)类似的功能。对于那些不了解MEF的人,我想要这样的东西:

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:

提供一个界面

public interface IFoo {
 ...
}    

通过查看已加载的jar,动态加载接口的实现。

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.

在Java中根本不可能吗?我发现一些Google命中说这是不可能的,但这似乎有点...嗯?

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.

推荐答案

在'pure'Java中,您可以使用ServiceLoader:
http://download.oracle.com/javase/6/docs/api /java/util/ServiceLoader.html

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

您只需在扩展jar中提供元数据,这很容易扩展,很聪明。

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

或者寻找像Guice或Spring这样的DI框架...

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

这篇关于动态加载Java接口的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆