Results 1 to 7 of 7
Thread: Return class by name
- 04-18-2012, 10:47 AM #1
Member
- Join Date
- Feb 2011
- Posts
- 8
- Rep Power
- 0
Return class by name
Say I have a program which declares an object of type Animal. The Animal class is an abstract class, which has subclasses including Pig, Dog and Sheep.
What I want to do is dynamically assign the Animal instance to one of its subclasses, given just the name of the subclass.
I've been trying things like this, which don't work:
Java Code:Animal animal; animal = Class.forName("Pig");
- 04-18-2012, 10:49 AM #2
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
Re: Return class by name
"which don't work" gives us next to no useful information.
What errors or excceptions do you get?Please do not ask for code as refusal often offends.
- 04-18-2012, 10:50 AM #3
Member
- Join Date
- Feb 2011
- Posts
- 8
- Rep Power
- 0
Re: Return class by name
Type mismatch: cannot convert from Class<capture#1-of ?> to Animal
- 04-18-2012, 11:44 AM #4
Re: Return class by name
What made you think that Class.forName(...) would return an instance of a class? have you read the API for java.lang.Class?
dbWhy do they call it rush hour when nothing moves? - Robin Williams
- 04-18-2012, 11:53 AM #5
Member
- Join Date
- Feb 2011
- Posts
- 8
- Rep Power
- 0
- 04-18-2012, 12:32 PM #6
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,413
- Blog Entries
- 7
- Rep Power
- 17
Re: Return class by name
When people rob a bank they get a penalty; when banks rob people they get a bonus.
- 04-18-2012, 02:02 PM #7
Senior Member
- Join Date
- Apr 2012
- Location
- New York State of Confusion, USA
- Posts
- 137
- Blog Entries
- 1
- Rep Power
- 0
Similar Threads
-
Read in Int from return method in other class?
By WoodyHD in forum New To JavaReplies: 6Last Post: 01-18-2012, 06:02 AM -
Class constructor with boolean return possible?
By KingdomX in forum New To JavaReplies: 3Last Post: 12-21-2011, 09:16 PM -
How to get a compatible class of a template class? Return type of method is AClass<E>
By SKuypers in forum Advanced JavaReplies: 0Last Post: 12-07-2011, 11:55 AM -
accessing return values from another class
By moaxjlou in forum New To JavaReplies: 3Last Post: 10-31-2008, 02:25 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks