ObjectInputStream resolveClass()方法

java.io.ObjectInputStream.resolveClass(ObjectStreamClass desc) 方法加载本地类相当于指定的流类的描述。子类可以实现此方法,允许类从备用源获取。

1 语法

protected Class<?> resolveClass(ObjectStreamClass desc)

2 参数

desc:类ObjectStreamClass的实例。

3 返回值

返回与desc相对应的Class对象。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.io.ObjectInputStream.resolveClass(ObjectStreamClass desc)方法的例子
 */
import java.io.*;

public class Demo extends ObjectInputStream {

    public Demo(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
            Demo ois = new Demo(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

热门文章

优秀文章