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