• Post Reply Bookmark Topic Watch Topic
  • New Topic

Instantiating a class  RSS feed

 
Dilshad Syed
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does anyone know a way to instantiate a class based on a classname in a String?
Thanks,
Dilshad
 
Blake Minghelli
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You want to use the forName() method of Class.
Like this:

 
Steve Weeks
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm a bit new to java development, so I appologize if my question is inappropriate. I'm a bit confused by the forName() code example posted. If I had a classname stored in a String variable called strMyClass, what would be the syntax for instantiating this class? Thanks so much.
 
David Yutzy
tumbleweed and gunslinger
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was curious on the topic and stopped by to see the response...
I'm not sure what was responded will actually work.

Calling forName() would get an instance of the class from a string, but having to set "MyClass" in the declaration and then cast it kinda invalidates the point of the question doesn't it?
I think what was asked was something like:

That would get you an instance of the "object" but not a dynamic, class-specific instance.
 
Blake Minghelli
Ranch Hand
Posts: 331
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Calling forName() would get an instance of the class from a string, but having to set "MyClass" in the declaration and then cast it kinda invalidates the point of the question doesn't it?

Good point. My code example works, but it's not a very good example, thanks.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!