Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Create class from a string

  Asked By: Lisa    Date: Feb 17    Category: Java    Views: 875

At runtime I read my fleet definition from a text file. At this
point I know I need to create a Tug with params P. I even know
this is going to be net.jumpspace.FT.Tug, that's stored in a
String str.

What I'd like to do is:

Ship shp=new str( P );

Is there any way to do this?



2 Answers Found

Answer #1    Answered By: Sonya Flores     Answered On: Feb 17

One way to implement this is using serialization,
because each constructor of a class  derived from Ship could can
different number of parameters.

I'm sending you an example, your Ship class is equivalent to
MiClaseSerializable, that class have to implement the interface
"Serializable" so Java is responsible to convert your class in
a serialized String without taking the attributes defined as
"transient", you can redefine the readObject method if you have
some transient attributes that you need to initialize each time
the object is readed and not created by the constructor, but
is not necessary.

In the Aplic class you can see how the program saves objects
("grabar" method) and read  them ("leer" method) from a text  file.
In the reading you can make reference to your superclass (Ship),
as i make reference to MiClaseSerializable, and because you will
read really Tug, a derived class from Ship, you wont have any
problem, that will be managed by poliformism.

In the example, I use a vector in the Aplic class, but you
can save and read directly your class, without using vectors,


Answer #2    Answered By: Eric Foster     Answered On: Feb 17

you can set up objects in an array, that way you don't have to give them a
variable, you can just refer to them from the array. I recommend a different
array for each type. The way these "ships" will interact with one another
should influence the data structure that you choose to implement. An array
might not be the best way of handling it. ? Good luck.
give some more info on how these ships will interact or not in the program if
you like.

Didn't find what you were looking for? Find more on Create class from a string Or get search suggestion and latest updates.