Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

"Casting" from a Superclass to a subclass

 
Sankar Sarma
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48409
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic