¿Cómo puedo averiguar qué tipo es cada objeto en una ArrayList?


Tengo una ArrayList compuesta de diferentes elementos importados de una db, compuesta de cadenas, números, dobles e ints. ¿Hay alguna manera de utilizar una técnica de tipo de reflexión para averiguar qué tipo de datos contiene cada elemento?

Para su información: La razón por la que hay tantos tipos de datos es que se trata de una pieza de código java que se está escribiendo para implementarse con diferentes BD.

Author: WolfmanDragon, 2008-09-20

12 answers

En C#:
Arreglado con la recomendación de 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);
    }
    ...
}

En 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:24

Puede usar el método getClass(), o puede usar instanceof. Por ejemplo

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

O

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

Tenga en cuenta que instanceof coincidirá con subclases. Por ejemplo, de C es una subclase de A, entonces lo siguiente será cierto:

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

Sin embargo, lo siguiente será falso:

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-19 23:23:24

Casi nunca quieres usar algo como:

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

Porque no estás contabilizando posibles subclases. Realmente quieres usar la clase # 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-21 00:04:18

En Java simplemente use el operador instanceof. Esto también se encargará de las subclases.

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-15 15:06:52

Simplemente llame a .getClass() en cada Object en un bucle.

Desafortunadamente, Java no tiene 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-01 20:11:00

Instanceof funciona si no depende de clases específicas, pero también tenga en cuenta que puede tener nulos en la lista, por lo que obj.getClass () fallará, pero instanceof siempre devuelve false en 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-20 00:04:53

Desde 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-10 11:12:57

En lugar de usar object.getClass().getName() puede usar object.getClass().getSimpleName(), porque devuelve un nombre de clase simple sin un nombre de paquete incluido.

Por ejemplo,

Object[] intArray = { 1 }; 

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

Da,

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-05 18:06:26

Dices "esto es una pieza de código java que se está escribiendo", de lo que infiero que todavía hay una posibilidad de que puedas diseñarlo de una manera diferente.

Tener una ArrayList es como tener una colección de cosas. En lugar de forzar la instanceof o getClass cada vez que toma un objeto de la lista, ¿por qué no diseñar el sistema de modo que obtenga el tipo del objeto cuando lo recupere de la base de datos y lo almacene en una colección del tipo de objeto apropiado?

O, usted podría usar una de las muchas bibliotecas de acceso a datos que existen para hacer esto por usted.

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-20 01:11:36

Si espera que los datos sean numéricos de alguna forma, y todo lo que le interesa hacer es convertir el resultado a un valor numérico, le sugeriría:

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-01 20:10:14