Java.io.ObjectInputStream.resolveClass()方法實例
java.io.ObjectInputStream.resolveClass(ObjectStreamClass desc) 方法加載本地類相當於指定的流類的描述。子類可以實現此方法,允許類從備用源獲取。
聲明
以下是java.io.ObjectInputStream.resolveClass()方法的聲明
protected Class<?> resolveClass(ObjectStreamClass desc)
參數
-
desc -- ObjectStreamClass類的一個實例
返回值
此方法返回對應遞減一個Class對象
異常
-
IOException -- 任何通常的輸入/輸出異常。
-
ClassNotFoundException -- 如果無法找到類的序列化對象。
例子
下麵的示例演示java.io.ObjectInputStream.resolveClass()方法的用法。
package com.yiibai; import java.io.*; public class ObjectInputStreamDemo extends ObjectInputStream { public ObjectInputStreamDemo(InputStream in) throws IOException { super(in); } public static void main(String[] args) { String s = "Hello World"; try { // create a new file with an ObjectOutputStream FileOutputStream out = new FileOutputStream("test.txt"); ObjectOutputStream oout = new ObjectOutputStream(out); // write something in the file oout.writeUTF(s); oout.flush(); // create an ObjectInputStream for the file we created before ObjectInputStreamDemo ois = new ObjectInputStreamDemo(new FileInputStream("test.txt")); // read and print an object and cast it as string System.out.println("" + (String) ois.readUTF()); // get the class for string and print the name ObjectStreamClass streamClass = ObjectStreamClass.lookup(Integer.class); System.out.println("" + ois.resolveClass(streamClass).getName()); } catch (Exception ex) { ex.printStackTrace(); } } }
讓我們編譯和運行上麵的程序,這將產生以下結果:
Hello World java.lang.Integer