aspose file tools*
The moose likes Beginning Java and the fly likes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark ""Casting" from a Superclass to a subclass" Watch ""Casting" from a Superclass to a subclass" New topic
Author

"Casting" from a Superclass to a subclass

Sankar Sarma
Greenhorn

Joined: Mar 26, 2009
Posts: 2
Hello All

I have a design question regarding the above:

I have a generic data class that has a variable list of attributes - each representing a column in a table (name, type etc.). I have a class that reads data from the database and populates instances of the data class (e.g., there is a load(ID, tableName) method that returns an instance of the data for the given table).

I also have a bunch of classes that extend the above class - these represent actual tables and have the actual attributes of each table. these are used as POJOs with getters and setters.


e.g






What I want to be able to do is to "cast" the generic data class as a POJO - e.g. when my Data instance is returned, I'd like to map the data values for each column to the actual instance variables in the subclass.


What would be an ideal design for something like this.

Thanks in advance.
Ryan Beckett
Ranch Hand

Joined: Feb 22, 2009
Posts: 192
I don't see a class named POJO nor a generic class. I thought you meant Java generics.

What I want to be able to do is to "cast" the generic data class as a POJO


You can downcast, but there's no compile-time error checking. So, you may get a ClassCastException.

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36590
    
  16
If those objects all implement the same interface, try to declare them of that interface type, then maybe you can avoid the class cast.
Sankar Sarma
Greenhorn

Joined: Mar 26, 2009
Posts: 2
Campbell Ritchie wrote:If those objects all implement the same interface, try to declare them of that interface type, then maybe you can avoid the class cast.

Thank you all for the reply (Sorry for the late ack, but I am new and I kept looking at 'My Posts' and it only shows my version )

The objects return a POJO that represents a 'table' with getters and setters for each field - the generic object has a map that holds reference to each field... I'll probably use a 'translator' service to map the mapped objects to actual attributes.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: "Casting" from a Superclass to a subclass
 
Similar Threads
JGrinder staff
Hibernate: Running a query using an object
Unable to define/override @Id(s) on a subclass; which classes i have to solve?
Runtime Creating Tables
Enum representing DB table.