Jak mogę dowiedzieć się, jakiego typu jest każdy obiekt w ArrayList?

Mam Arraylistę składającą się z różnych elementów importowanych z db, składającą się z ciągów znaków, liczb, Dubli i intów. Czy istnieje sposób, aby użyć techniki typu odbicia, aby dowiedzieć się, co każdy rodzaj danych zawiera każdy element?

FYI: powodem, dla którego istnieje tak wiele typów danych, jest to, że jest to fragment kodu Javy, który jest pisany do implementacji z różnymi bazami danych.

Author: WolfmanDragon, 2008-09-20

12 answers

In C#:
Fixed with Mike

ArrayList list = ...;
// List<object> list = ...;
foreach (object o in list) {
    if (o is int) {
        HandleInt((int)o);
    }
    else if (o is string) {
        HandleString((string)o);
    }
    ...
}

W Języku Java:

ArrayList<Object> list = ...;
for (Object o : list) {
    if (o instanceof Integer)) {
        handleInt((int)o);
    }
    else if (o instanceof String)) {
        handleString((String)o);
    }
    ...
}
 99
Author: Frank Krueger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:18:24

Możesz użyć metody getClass(), lub możesz użyć instanceof. Na przykład

for (Object obj : list) {
  if (obj instanceof String) {
   ...
  }
}

Lub

for (Object obj : list) {
 if (obj.getClass().equals(String.class)) {
   ...
 }
}

Zauważ, że instanceof będzie pasował do podklas. Na przykład, of C jest podklasą A, wtedy prawda będzie następująca:

C c = new C();
assert c instanceof A;

Jednakże, następujące będą fałszywe:

C c = new C();
assert !c.getClass().equals(A.class)
 54
Author: faran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-01 20:10:47
for (Object object : list) {
    System.out.println(object.getClass().getName());
}
 44
Author: Fabian Steeg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-19 23:23:24

Prawie nigdy nie chcesz używać czegoś takiego jak:

Object o = ...
if (o.getClass().equals(Foo.class)) {
    ...
}

Ponieważ nie liczysz możliwych podklas. Naprawdę chcesz użyć klasy # isAssignableFrom:

Object o = ...
if (Foo.class.isAssignableFrom(o)) {
    ...
}
 13
Author: Heath Borders,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-21 00:04:18

W Javie wystarczy użyć operatora instanceof. To również zajmie się podklasami.

ArrayList<Object> listOfObjects = new ArrayList<Object>();
for(Object obj: listOfObjects){
   if(obj instanceof String){
   }else if(obj instanceof Integer){
   }etc...
}
 5
Author: Reid Mac,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-10-13 14:35:50
import java.util.ArrayList;

/**
 * @author potter
 *
 */
public class storeAny {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList<Object> anyTy=new ArrayList<Object>();
        anyTy.add(new Integer(1));
        anyTy.add(new String("Jesus"));
        anyTy.add(new Double(12.88));
        anyTy.add(new Double(12.89));
        anyTy.add(new Double(12.84));
        anyTy.add(new Double(12.82));

        for (Object o : anyTy) {
            if(o instanceof String){
                System.out.println(o.toString());
            } else if(o instanceof Integer) {
                System.out.println(o.toString());   
            } else if(o instanceof Double) {
                System.out.println(o.toString());
            }
        }
    }
}
 5
Author: potter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-15 15:06:52

Po prostu wywołaj .getClass() Na każdym Object W pętli.

Niestety, Java nie ma map(). :)

 4
Author: skiphoppy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-01 20:11:00

Instanceof działa, jeśli nie zależy ci na konkretnych klasach, ale pamiętaj również, że możesz mieć null na liście, więc obj.getClass() nie powiedzie się, ale instanceof zawsze zwraca false NA null.

 3
Author: John Gardner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-20 00:04:53

Od Java 8


        mixedArrayList.forEach((o) -> {
            String type = o.getClass().getSimpleName();
            switch (type) {
                case "String":
                    // treat as a String
                    break;
                case "Integer":
                    // treat as an int
                    break;
                case "Double":
                    // treat as a double
                    break;
                ...
                default:
                    // whatever
            }
        });
 3
Author: Andrey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-10 11:12:57

Zamiast object.getClass().getName() możesz użyć object.getClass().getSimpleName(), ponieważ zwraca prostą nazwę klasy bez dołączonej nazwy pakietu.

Na przykład,

Object[] intArray = { 1 }; 

for (Object object : intArray) { 
    System.out.println(object.getClass().getName());
    System.out.println(object.getClass().getSimpleName());
}

Daje,

java.lang.Integer
Integer
 2
Author: Sufiyan Ghori,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-05 18:06:26

Mówisz "to jest kawałek kodu Javy, który jest pisany", z czego wnioskuję, że nadal jest szansa, że mógłbyś zaprojektować go inaczej.

Posiadanie ArrayList jest jak posiadanie kolekcji rzeczy. Zamiast wymuszać instanceof lub getClass za każdym razem, gdy bierzesz obiekt z listy, dlaczego nie zaprojektować systemu tak, aby uzyskać typ obiektu po pobraniu go z DB i zapisać go w kolekcji odpowiedniego typu obiektu?

Or, you może użyć jednej z wielu bibliotek dostępu do danych, które istnieją, aby to zrobić za Ciebie.

 0
Author: shoover,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-20 01:11:36

Jeśli oczekujesz, że dane będą liczbowe w jakiejś formie, a wszystko, co Cię interesuje, to konwersja wyniku na wartość liczbową, proponuję:

for (Object o:list) {
  Double.parseDouble(o.toString);
}
 0
Author: DJClayworth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-01 20:10:14