Should I be learning XML in tandem with Java?

除非您想学习XML或认为XML是您的应用程序的一个很好的选择,否则没有理由.有许多方法可以在没有XML的情况下进行序列化

Doesn’t my IDE, upon succesful compilation, know how many objects I have, their data type, and what class they belong to?

不,它不必.由于分配是在Java中动态完成的,因此有些情况甚至无法静态地知道这些信息.

Foo[] foos = new Foo[ new Scanner(System.in).nextInt() ];

for(int i = 0; i < foos.length; ++i)

foos[i] = new Foo();

(创建了多少个Foos?编译器不知道.)

当然,编译器对数据类型有很多了解.

B) Is there a way to save ALL objects without specifying them individually.

也许使用Serializable.基本上,您将所有程序状态放在一个对象中.序列化该单个对象时,其他所有内容都会以递归方式序列化.

class FooState implements Serializable {

Integer a, b, c; // Integer and String

String d, e, f; // also implement Serializable

}

class Foo {

static FooState allMyState = new FooState();

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

try(ObjectOutputStream oos = new ObjectOutputStream(

new FileOutputStream(new File("myFile.data")))) {

// no need to specify members individually

oos.writeObject(allMyState);

}

}

}

相同的概念可能适用于其他序列化方案,如JSON,XML等.

您需要仔细考虑放入状态对象的内容,因为其中的所有内容都将被保存.

c) Have I overdramitized the complexity of saving a simple program?

并不是的.如果不仅仅是几个值,保存程序状态可能很复杂.

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐