请各位帮忙看一下这个问题:
在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;
    }
}

解决方案 »

  1.   

    javax.naming.Reference
    着不到这个类,你的包是否引用够了?
      

  2.   

    不是找不到“javax.naming.Reference” 这个类。Object obj =ctx.lookup("tmp/myBoundObject");
    System.out.println("Class Name is : " + obj.getClass().getName());            
    上面这句print打印出来的结果是obj是javax.naming.Reference对象,但是他应该是MyObject对象才对,因此下面的转型就抛出了
    java.lang.ClassCastException: javax.naming.Reference // Exception from below code
     MyObject myobj = (MyObject)obj;  我引用的包除了jdk1.5外,还有fscontext.jar, providerutil.jar
    但似乎实现Referenceable的对象在帮定后再取出来时没有被Class Load成功,因而返回给我的还是Reference对象。 哪位大虾能够帮忙看看,感激不尽!!
      

  3.   

    这个jndi server是专门为文件系统服务的,随便绑一个对象不太好吧。有空反编译下com.sun.jndi.fscontext.FSContextFactory,看看它的getObjectInstance()方法。如果我没猜错,所有的可解析reference对象(指类型都是com.sun.jndi.fscontext.FSContext$FSFile)都将被正确地返回确切信息,否则直接返回reference,直接转就出错了这属于JNDI SPI的问题