Skip to content

Instantly share code, notes, and snippets.

@codenameone
Last active July 8, 2020 09:57
Show Gist options
  • Save codenameone/858d8634e3cf1a82a1eb to your computer and use it in GitHub Desktop.
Save codenameone/858d8634e3cf1a82a1eb to your computer and use it in GitHub Desktop.
public Main {
public void init(Object o) {
theme = UIManager.initFirstTheme("/theme");
// IMPORTANT: Notice we don't use MyClass.class.getName()! This won't work due to obfuscation!
Util.register("MyClass", MyClass.class);
}
public void start() {
//...
}
public void stop() {
//...
}
public void destroy() {
//...
}
}
public MyClass implements Externalizable {
// allows us to manipulate the version, in this case we are demonstrating a data change between the initial release
// and the current state of object data
private static final int VERSION = 2;
private String name;
private Map<String, Object> data;
// this field was added after version 1
private Date startedAt;
public int getVersion() {
return VERSION;
}
public void externalize(DataOutputStream out) throws IOException {
Util.writeUTF(name, out);
Util.writeObject(data, out);
if(startedAt != null) {
out.writeBoolean(true);
out.writeLong(startedAt.getTime());
} else {
out.writeBoolean(false);
}
}
public void internalize(int version, DataInputStream in) throws IOException {
name = Util.readUTF(in);
data = (Map<String, Object>)Util.readObject(in);
if(version > 1) {
boolean hasDate = in.readBoolean();
if(hasDate) {
startedAt = new Date(in.readLong());
}
}
}
public String getObjectId() {
// IMPORTANT: Notice we don't use getClass().getName()! This won't work due to obfuscation!
return "MyClass";
}
}
// will read the file or return null if failed
MyClass object = (MyClass)Storage.getInstance().readObject("NameOfFile");
// write the object back to storage
Storage.getInstance().writeObject("NameOfFile", object);
@codenameone
Copy link
Author

Sample usage of Externalizable interface.

From the Codename One project

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment