您的位置:首页 > 其它

ServiceLoader使用和创建组件的内容区分开来

2010-10-29 00:00 246 查看
package com.cn.test.beanload;

public interface IPersonalServant {

// Process a file of commands to the servant

public void process(java.io.File f)

throws java.io.IOException;

public boolean can(String command);

}

package com.cn.test.beanload;

import java.io.File;

public class Jeeves implements IPersonalServant {

public void process(File f) {

System.out.println("Very good, sir.");

}

public boolean can(String cmd) {

if (cmd.equals("fetch tea"))

return true;

else

return false;

}

}

package com.cn.test.beanload;

import java.io.File;

import java.io.IOException;

import java.util.ServiceLoader;

public class Servant {

public static void main(String[] args)

throws IOException

{

ServiceLoader servantLoader =

ServiceLoader.load(IPersonalServant.class);

IPersonalServant i = null;

for (IPersonalServant ii : servantLoader)

if (ii.can("fetch tea"))

i = ii;

if (i == null)

throw new IllegalArgumentException("No suitable servant found");

for (String arg : args)

{

i.process(new File(arg));

}

}

}

使用时需要META-INF/services/com.cn.test.beanload.IPersonalServant 文件

内容为com.cn.test.beanload.Jeeves

将项目打包成jar后,加入工程,调用Servant .
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐