java doubt...

Started by
5 comments, last by polly 18 years, 4 months ago
Hi, How can I create a new object of a type given by a String ? For example: I have a class Table with default constructor: public Table(int id, int size) { // ... } And I want to create a new instance of this class using this constructor, given only the String "Table" (the class name)... how can i do this? Huge thx
"Through me the road to the city of desolation,Through me the road to sorrows diuturnal,Through me the road among the lost creation."
Advertisement
You would have to do a series of if statements of a switch-case.

ace
thats exactly what im trying to avoid... i dont know in advance the type of the object i want to create.

I believe it should have something to do with the class Class, and methos forName, isInstance, etc... but i've looked at some code, and it didnt make much sense to me... :( please help
"Through me the road to the city of desolation,Through me the road to sorrows diuturnal,Through me the road among the lost creation."
You can use the Java reflection API (java.lang.reflect).

For example given a string className you can get the relevant class object and create an instance with:
Class classDefinition = Class.forName(className);Object object = classDefinition.newInstance();

To do it with constructors that have arguments is slightly more complicated, and you should see the example in the reflection API docs for that.
You can convert from a string into a Class object with Class.forName(String). However I think this requires a full class name (ie. with the package preamble).

From this you can use Class.newInstance() to create an object using the default constructor. If you want to invoke a specific constructor you'll have to poke around the class object using reflection to find the correct constructor.

Edit: too slow. [grin]
Rather than getting too deep into the Reflection API, you might be better served giving your Table class an init method which takes the same arguments as your constructor. Then after you create the instance via Class.newInstance, you just call the init method. I make use of dynamic instantiation often in Java projects and use this approach.
The reflection API is one possibility, or you could write a factory class which produces objects of type .. whatever.

It really depends upon the domain objects you are using. A factory class would be more appropraite if you had a superclass (or interface) for your Table class, and other classes implemented the same interface/extended that parent class. Then you could write a factory to produce objects of the superclass.

If you are producing a new Table from the String "Table", then where are you getting the int values from? Are they default values somewhere, are they specified by another class?

Jon

This topic is closed to new replies.

Advertisement