Question

Is it even possible? I need to be able to read from the file later on. example of what I intend doing (but doesn't work because E isn't Serializable):

private <E> void writeEvent(ObjectOutputStream out,E obj) throws IOException{
        out.writeObject(new custEvent(obj));
        }

class custEvent<E> implements Serializable{
        private E obj;
        private Date date;

        public custEvent(E obj) {
            this.obj=obj;
            date=new Date();
        }
    }
Was it helpful?

Solution

Why don't you use use an upper bound in your generic parametrization for E?

As in:

private <E extends Serializable> void writeEvent(ObjectOutputStream out,E obj) {
  // etc.
}

The confusion here would be that Serializable is an interface and cannot be "extended" by classes (but it can be extended by other interfaces as Thomas remarks), but the upper bound is still valid.

Of course this implies that your Es will need to implement Serializable, or implement an interface that extends Serializable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top