让我们首先说明属于其中的(基)类:
// the data class. This contains our values
public class Data<T extends Annotation> {
public transient final T info; // gson ignores transients
public Data(Class<T> annotation) { info = getClass().getAnnotation(annotation); }
}
// the manager class, this contains numerous Data's
public class Manager<T> {
protected final ArrayList<T> collection = new ArrayList<T>();
public Collection<T> GetCollection() { return collection; }
}
现在假设我已经按照以下方式实现了上述类:
// my implemented manager. It contains a bunch of MyBase objects
public class MyManager extends Manager<MyBase> {
public MyManager() {
collection.add(new MyCustomBase());
// some more...
}
}
public class MyBase extends MyData {
// some stuff for my base, such as various methods for calculating and rendering
}
public MyData extends Data<MyData.MyInterface> {
public String foo;
MyData() {
super(MyData.MyInterface.class);
foo = info.foo(); // handle our interface variables, since interfaces cannot be directly modified
}
@Retention
public @interface MyInterface {
String foo();
}
为了使代码易于理解,我的自定义库如下所示:
@MyData.MyInterface(foo = "bar")
public class CustomBase extends MyBase {
// other various methods for rendering and calculating, some events in here too
}
现在,在GSON中,我想从MyData中打印出信息。这是我尝试执行此操作的方式:
public class Config {
// store the 'Managers' which we want to save the data of inside of an arrayList, and then iterate through them and their contents for 'Data', then just save it.
//...
Gson gson = new GsonBuilder().setPrettyPrinting().create();
PrintWriter writer = new PrintWriter(myJSON);
for (Manager m : managerList) {
for (Object o : m.GetCollection()) {
Data d = (Data) o;
// expected result, a json with "foo": bar
writer.println(gson.toJson(d)); // this doesn't work, throws a stack overflow
}
writer.close();
}
不幸的是,这种方法不起作用。由于某些奇怪的原因,它引发了堆栈溢出。有什么更好的方法呢?
编辑:自foo之后,我将不会直接处理该接口,否则在程序执行过程中其他任何值都会更改。
答案 0 :(得分:0)
我已经设法通过使用@Expose注释来避免此问题:
"<Shift><Primary>"
然后,在使用GsonBuilder创建Gson时,只需使用<Primary>
。