• Post Reply Bookmark Topic Watch Topic
  • New Topic

how to create object of a class whose name is contained in a string  RSS feed

 
Rajiv Chelsea
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
lets suppose

String className = com.rajiv.SomeClass

How can i make an object of SomeClass?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out the methods of the java.lang.Class class. (In particular, you want to look at forName() and newInstance()). That should give you what you want.
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since this is the beginning Java section I want to ask you this: why do you want this? Because reflection (which you're going to use with the Class methods) is not a beginning Java topic and you lose a lot of advantages that you have with regular Java.
 
Rajiv Chelsea
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can do the following

Class.forName(className).newInstance();

but the above line of code returns an object
How do i recast it to SomeClass which is the original class name.
 
Paul Beckett
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You may need to think a little bit about what you are asking. If you are reading a class name from a String and you don't know what the class is until runtime then what are you going to cast it to?

However if you have a class hierarchy such as:

class Shape{}
class Circle extends Shape{}
class Square extends Shape{}

and you *always* read the subclass of Shape then you can cast to the Shape superclass. If you can complete all the logic you need via a variable of type Shape then fine. If not you may need to use a conditional block that checks which subtype of Shape your instanceof is and then casts to the appropriate subtype.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!