http://java.sun.com/products/jndi/downloads/index.html
Let's do the world famous Hello World application.
Hello.java
1 2 3 4 5 6 | package myproject; public interface Hello { public String getMessage(); } |
HelloImpl.java
1 2 3 4 5 6 7 8 9 | package myproject; public class HelloImpl implements Hello { @Override public String getMessage() { return "Hello World" ; } } |
HelloFactory.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | package myproject; import java.util.Hashtable; import javax.naming.Context; import javax.naming.Name; import javax.naming.spi.ObjectFactory; public class HelloFactory implements ObjectFactory { @Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception { return new HelloImpl(); } } |
Main.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package myproject; import java.util.Hashtable; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.Reference; public class Main { public static void main(String[] args) throws Exception { Hashtable<String, String> env = new Hashtable<string, string= "" >(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory" ); InitialContext ic = new InitialContext(env); Reference ref = new Reference(Hello. class .getName(), HelloFactory. class .getName(), null ); ic.rebind( "whatever/object" , ref); System.out.println(((Hello) ic.lookup( "whatever/object" )).getMessage()); } } </string,> |
No comments:
Post a Comment