请各位帮忙看一下这个问题:
在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;
}
}
在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;
}
}
着不到这个类,你的包是否引用够了?
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对象。 哪位大虾能够帮忙看看,感激不尽!!