Dynamically set List <type>

Earlier, I used reflection to do things like dynamically retrieve a class and set the values ​​of the fields in it. My search on Google showed me that I can also use reflection for a dynamic tick.

My code is as follows:

import entity.Shipvia;
import entity.Route;
import java.lang.reflect.Field;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class RetrieveResultList {

    public static List retrieveResultList(String tablename) {
        EntityManager entityManager = Persistence.createEntityManagerFactory("EntityLibraryPU").createEntityManager();
        Query query = entityManager.createNamedQuery(tablename + ".findAll");
        List<Shipvia> resultList = query.getResultList();
        return resultList;
    }
}

I use this method to dynamically retrieve the result from a database table. Since the table name is always different, I cannot have a List, because it will be different for each table.

How do I go about converting the tablename string that I go to to be a list type?

+5
source share
1 answer

, , , Java, , , , , .

, , String . , ( , ), , .

:

List<Shipvia> shipvias = RetrieveResultList.retrieveResultList( Shipvia.class );

:

public class RetrieveResultList {

    private static final EntityManagerFactory FACTORY = Persistence.createEntityManagerFactory("EntityLibraryPU");

    public static <T> List<T> retrieveResultList(Class<T> type) {
        EntityManager entityManager = FACTORY.createEntityManager();
        String tablename = type.getName(); // figure out table name from **type**
        Query query = entityManager.createNamedQuery(tablename + ".findAll");
        List<T> resultList = query.getResultList();
        entityManager.close();
        return resultList;
    }
}

- , .

, factory , factory , . EntityManager, .

+5

All Articles