(This class is a Jpanel based and some references to another classes)mypackage.myclass
tonnot wrote:No, it's not necessary usually and when you don't know the type at compile time, then it's not possible either.
Now I have 3 questiosn - problems:
1.- I dont know the class name (or I want that my code works with every kind of object) ,so... Is it neccesary to CAST the object?
2.- In this case.... it can be done by mean of string name ? aux = (the_cast) .... ( when the_cast = "MYclass")No, that's not possible. Since casting doesn't change anything about the object but only about the reference, casting "to a dynamic type" is meaningless, since you couldn't have a reference variable "of a dynamic type" to hold the newly-cast object anyway.
3.- Finally I dont know how to create an instance of my new classThe problem is that you're trying to cast the Class object to MY_CAST (which I assume is your class), while it should in fact be a Class<? extends MY_CAST>.
((MY_CAST) aux.getclass()).newinstance(); throws an error of "java.lang.Class cannot be cast ..."
tonnot wrote:You already did that! During deserialization a new object was already created!
My intention is to write a program to serialize - deserialize any class.
I know which serialized class I want because I know the name of the file I want to deserialize....Ok, but why do you think you need to call newInstance() on anything in order to deserialize? There's no need to do that.
tonnot wrote:No, you have a much more basic problem.
Perhaps serialize classes with swing components are the problem ?
I have read that it is recommended to use XMLencoder to do this, is it true ?That is true. But I don't think that this particular issue is the problem you face right now.
By the moment I go to stop learn about serialization-deserializationMy suggestion: you should learn about serialization in a context outside of a current problem.
it can be done with this 2 methods:OK. So why do you need 1 and 2?
1.- MYClass d = new MYclass;
2.- Object d = Class.forName("mypackage.MYclass").newInstance()
In this situation before to read the file I can create the object with
MYclass d = (MYclass) s.readObject(); (s is the ObjectInputStream)
What is I read?Whatever you wrote to it. What did you write to it?