Why am I getting java.lang.ClassCastException ?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • phpuser123
    New Member
    • Dec 2009
    • 108

    Why am I getting java.lang.ClassCastException ?

    Here are the codes I just compiled in java and I am getting a java.lang.Class CastException ...


    Code:
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutput;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    import java.util.Date;
    
    public class test_serialisation implements Serializable{
    
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 1L;
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		FileOutputStream f;
    		try {
    			f = new FileOutputStream("tmp");
    			ObjectOutput s = new ObjectOutputStream(f);
    			s.writeObject("Today");
    			s.writeObject(new Date());
    			s.flush();
    			FileInputStream in = new FileInputStream("tmp");
    			ObjectInputStream ss = new ObjectInputStream(in);
    			
    			Object dt=(Object)ss.readObject();
    			Date dtt=((Date) dt);
    			
    			System.out.println(dtt);
    } catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		
    	}
    
    }
    and my printstack is
    Code:
    java.lang.ClassCastException: java.lang.String
    	at test_serialisation.main(test_serialisation.java:33)
    I cannot understand properly what it means since I am now learning java serialisation.. I awould appreciate any help..
    Last edited by Nepomuk; Oct 13 '10, 10:00 AM. Reason: Corrected [CODE] tags
  • improvcornartist
    Recognized Expert Contributor
    • May 2007
    • 303

    #2
    The full error is
    Code:
    java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Date
            at test_serialisation.main(test_serialisation.java:33)
    and occurs on
    Code:
    Date dtt=((Date) dt);
    It doesn't like that you are trying to convert a string to a date.

    Comment

    Working...