JDK-5092105 : classes with generic members can't specialize readObject() without a warning
  • Type: Enhancement
  • Component: tools
  • Sub-Component: javac
  • Affected Version: 5.0
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: solaris_2.5.1
  • CPU: x86
  • Submitted: 2004-08-25
  • Updated: 2004-11-23
  • Resolved: 2004-11-23
Related Reports
Duplicate :  
Description

Name: gm110360			Date: 08/25/2004


A DESCRIPTION OF THE REQUEST :
class G1<T>  implements Serializable {}

class G2<T> implements Serializable
{
    protected G1<T> g1_instance;

    private void readObject(ObjectInputStream in) throws IOException
    {
        try {
            g1_instance = (G1<T>) in.readObject();
        } catch (ClassCastException e) {}
        } catch (ClassNotFoundException e) {}
    }
}

This gives a compiler warning, as specified in the generics tutorial.  However,
the implications are that no class containing a generic type may specialize
the serializablity mechanism without a warning.

JUSTIFICATION :
  Since serialization is an often used language feature, and one hopes that generics will be as well, it would be nice if one could use the two mechanisms together without compiler warnings.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
I'm not a generics expert, but perhaps adding a generic method to ObjectInputStream

<T> T readGeneric()

would help with this.

ACTUAL -
A compiler warning is issued using two standard language mechanisms together.

---------- BEGIN SOURCE ----------
import java.io.Serializable;
import java.io.IOException;

class G1<T> implements Serializable {}

class G2<T> implements Serializable
{
   protected G1<T> g1_instance;
   private void readObject(ObjectInputStream in) throws IOException
    {
        try {
            g1_instance = (G1<T>) in.readObject();
        } catch (ClassCastException e) {}
        } catch (ClassNotFoundException e) {}
    }
}

---------- END SOURCE ----------
(Incident Review ID: 297700) 
======================================================================

Comments
EVALUATION This is not a bug. readObject() cannot be made typesafe, and so the warning is mandatory. The best solution is to avoid serialization, at least for generic classes. ###@###.### 2004-08-25 The problem is that the proposed solution would require the value of the type variable T to be known at runtime. Due to erasure this information is simply not available at runtime. ###@###.### 2004-08-25
25-08-2004