日期:2014-05-20  浏览次数:20704 次

JNDI问题:Jndi访问FSSP时,lookup报“java.lang.ClassCastException: javax.naming.Reference”
请各位帮忙看一下这个问题:
在jndi访问File System Service Provider(FSSP)时,先是bind一个reference,然后用lookup取出后,转型时报出异常:
java.lang.ClassCastException: javax.naming.Reference
怎么解决这个问题啊?

Code:
public static void main(String[] args){
     try{
            Hashtable env = new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
            env.put(Context.PROVIDER_URL, "file:///D:/workspace/SampleApp");
            Context ctx = new InitialContext(env);            
            ctx.rebind("tmp/myBoundObject",new MyObject());
            Object obj =ctx.lookup("tmp/myBoundObject");
         System.out.println("Object is : " + obj.toString());
            System.out.println("Class Name is : " + obj.getClass().getName());            
            // Exception from below code
            MyObject myobj = (MyObject)obj;            
            
        }catch(NamingException ne){
            ne.printStackTrace();
            System.out.println("Problem is : " + ne);
        }
    }



如下是MyObject Class
public class MyObject implements Referenceable{
String myobj = "MyObject to String";
        
    public Reference getReference(){
     return new Reference(MyObject.class.getName());
    }
    
    public void printMessage(){
        System.out.println("This is instance of MyObject");
    }
    
    public String toString(){
        return myobj;
    }
}
------最佳解决方案--------------------
javax.naming.Reference
着不到这个类,你的包是否引用够了?
------其他解决方案--------------------
这个jndi server是专门为文件系统服务的,随便绑一个对象不太好吧。

有空反编译下com.sun.jndi.fscontext.FSContextFactory,看看它的getObjectInstance()方法。

如果我没猜错,所有的可解析reference对象(指类型都是com.sun.jndi.fscontext.FSContext$FSFile)都将被正确地返回确切信息,否则直接返回reference,直接转就出错了

这属于JNDI SPI的问题
------其他解决方案--------------------
不是找不到“javax.naming.Reference” 这个类。