JNDI(Java Naming and Directory Interface,Java命名和目录接口)是一组在Java应用中访问命名和目录服务的API。命名服务将名称和对象联系起来,使得我们可以用名称访问对象。目录服务是一种命名服务,在这种服务里,对象不但有名称,还有属性。 “还有属性”是个什么?
例子,访问文件系统:需要把两个jar:fscontext.jar和providerutil.jar加入到你的CLASSPATH中。
- public class Lookup {
- public static void main(String[] args) {
- Hashtable<String, String> env = new Hashtable<String, String>();
- env.put(Context.INITIAL_CONTEXT_FACTORY,
- "com.sun.jndi.fscontext.RefFSContextFactory");
- String name = "F://ecclient";
- try {
- // Create the initial context
- Context ctx = new InitialContext(env);
- // Look up an object
- Object obj = ctx.lookup(name);
- // Print it
- System.out.println(name + " is bound to: " + obj + "/t"
- + obj.getClass());
- } catch (NamingException e) {
- System.err.println("Problem looking up " + name + ": " + e);
- }
- }
- }
打印结果
- F:/ecclient is bound to: com.sun.jndi.fscontext.RefFSContext@901887 class com.sun.jndi.fscontext.RefFSContext