How to serialize a class with an interface?

Here is a generic solution that works for all cases where only interface is known statically. Create serialiser/deserialiser: final class InterfaceAdapter<T> implements JsonSerializer<T>, JsonDeserializer<T> { public JsonElement serialize(T object, Type interfaceType, JsonSerializationContext context) { final JsonObject wrapper = new JsonObject(); wrapper.addProperty(“type”, object.getClass().getName()); wrapper.add(“data”, context.serialize(object)); return wrapper; } public T deserialize(JsonElement elem, Type interfaceType, JsonDeserializationContext context) … Read more

Traits vs. interfaces

Public Service Announcement: I want to state for the record that I believe traits are almost always a code smell and should be avoided in favor of composition. It’s my opinion that single inheritance is frequently abused to the point of being an anti-pattern and multiple inheritance only compounds this problem. You’ll be much better … Read more

The purpose of interfaces continued

Interfaces are the only way to create multiple inheritance in Java. Say you create a class Animal. And all animals, including humans extend that. And each of those animals inherits common methods like eat, breathe, etc. But now let’s say you have a MathProblem class. And you want to have certain classes that can solve … Read more

Difference between Fortran’s “abstract” and “normal” interfaces

The “normal” interfaces — known by the standard as specific interface blocks (as you use in the title of the question) — are just normal interface blocks for some procedure. Therefore: interface subroutine foo_sub end subroutine end interface means that there exists an actual (external) subroutine named foo_sub and it conforms to the specified interface. … Read more

How does a generic constraint prevent boxing of a value type with an implicitly implemented interface?

My question, however, is how the compiler enables a generic constraint to eliminate the need for boxing a value type that explicitly implements an interface. By “the compiler” it is not clear whether you mean the jitter or the C# compiler. The C# compiler does so by emitting the constrained prefix on the virtual call. … Read more