java如何拿到接口对象_java - 如何返回接口对象?_java_酷徒编程知识库

可以使用ObjectOutputStream将对象保存到文件中,然后使用ObjectInputStream导入对象,

我写了一个小示例程序,import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;

public class Main {

public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {

A a = new A();

B b = new B();

save(a);

C c = load();

System.out.println(c.getClass()); // prints"A"

if (c instanceof A) {

System.out.println("is of class A");

A loaded = (A) c;// you can now use this object

System.out.println(a.someMethod());

} else if (c instanceof B) {

System.out.println("is of class B");

B loaded = (B) c;

} else {

System.out.println("should not occur");

}

}

private static C load() throws IOException, FileNotFoundException, ClassNotFoundException {

ObjectInputStream in = new ObjectInputStream(new FileInputStream("f.txt"));

C s = (C) in.readObject();

in.close();

return s;

}

private static void save(C c) throws FileNotFoundException, IOException {

final FileOutputStream fout = new FileOutputStream("f.txt");

final ObjectOutputStream out = new ObjectOutputStream(fout);

out.writeObject(c);

out.flush();

out.close();

}

}

class A implements C {

// serialVersion is the version of the clas, so if you save the object with

// serialVersion 1 and then change something, change this version to two, so you

// get an error if you are trying to load"obsolete" objects

private static final long serialVersionUID = 1L;

@Override

public String getName() {

return"A";

}

public String someMethod() {

return"someMethod";

}

}

class B implements C {

private static final long serialVersionUID = 1L;

@Override

public String getName() {

return"B";

}

public String someOtherMethod() {

return"someOtherMethod";

}

}

interface C extends Serializable { //Objects saved to a File have to be Serializable

String getName();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值