Typecasting with Class object
I am developing a JTable component that takes an entity class object (using hibernate) as a parameter. Basically it displays all of the database table corresponding to the class it receives as a parameter. To retrieve the data i am using a list that retrieves using the passed Class object, as such :
I get the correct list elements when doing that. The problem is that i dont know how to typecast the Objects that are read from this list to my Class parameter's class when i browse through the list. I have a basic skeleton :
public List getEntityList(Class entityClass)
Session session = factory.getCurrentSession();
List entityList = session.createQuery("FROM " + entityClass.getName()).list();
and the SOP call prints the correct Hibernate.Contact class. The entityClass variable is the class object that is being passed to the JTable (in this case, Hibernate.Contact). What i need to do is typecast the element object to this class without explicitely writing Contact contact = (Contact)element; as this class could change depending on what i want to display in the table.
for (Iterator iter = entityList.iterator(); iter.hasNext();)
Object element = iter.next();
int listPos = 0;
I have already used reflection to get the class fields to display in the JTable's column headers, as such :
private void initializeHeaders()
Field fields = entityClass.getDeclaredFields();
headers = new String[fields.length];
for (int i = 0; i < fields.length; i++)
headers[i] = fields[i].getName();
I looked on google for ways to achieve what i'm trying to do using reflections but found nothing.
Long story short, is it possible to typecast an Object object to the type of a Class paramter and then be able to use it's get/set methods?