简体   繁体   中英

How to read data from list<Object> in Java?

I have a list of objects List , being the result of a HQL Query. The Objects of the list contain the data I need. I am doing the following if I know the types of the data :

(Here I know that the query was Select country, globalAmount, average from table )

 for (Object record : result) {
            Object[] fields = (Object[]) record;
            String country =  (String) fields[0];
            long globalAmount = (Long) fields[1];
            double average = (Double) fields[2];
            System.out.println("Country "+country );
            System.out.println("Global Amount "+globalAmount);
            }  

The problem is that sometimes, I don't know if I'll be having "Country" or "average" in the Object, and the query can be completely different :

Select average, date, message from table

Then, to retreive data, I have to do the following :

 for (Object record : result) {
        Object[] fields = (Object[]) record;
        double average = (Double) fields[0];
        Timestamp date=  (Timestamp) fields[1];
        String message = (String) fields[2];

        System.out.println("date " +date);
        System.out.println("Message  "+Message);
        System.out.println("Average " + Average);

        }  

Is there any way that I can dynamically retreive data from this List without having Cast problems?

Thank you for your help!

This is just a proto-type. What I did here is got all the column names and then based on the column name I'm type casting it to the required type.

This is just a small trick.

String query = "Select x, y, z from tablename";
//get the columns here
String colums = query.substring(7, query.indexOf("from") - 1).trim();
String []arrColums = colums.split(",");
for(int i = 0; i < arrColums.length; i++)
{
    switch(arrColums[i])
     {
        case "X" : X x = (X)result.get(i);
        case "Y" : Y y = (Y)result.get(i);
     } 
}

It does not to seem possible. I had to use If blocks to figure out which type I am receiving. Quite long but did not have any other option. The solution provided by Uma Kanth is smart but was not suitable for me though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM