Check the arrayList object at runtime

2

I have an arraylist with three positions. I added to the array, objects of the type Manager, Salesman and Technician, respectively. Using getClass , I would like to know how to do which object is in each vector position.

I did this, but it did not generate any errors and did not call my methods.

public static void mostrarSalarioFuncionario() {

        ArrayList<Funcionario> listaFunc = new ArrayList<Funcionario>();
        listaFunc.add(ge);
        listaFunc.add(te);
        listaFunc.add(ve);
        System.out.println("CALCULO SALARIO DO FUNCIONARIO");
        for (int i = 0; i < listaFunc.size(); i++) {


            if (listaFunc.get(i).getClass().equals(ge) {
                System.out.println("Classe...:Gerente");
                System.out.println("Salário..:"+ge.calcularSalario());;
            }

            else if(listaFunc.get(i).getClass().equals(ve)) {
                System.out.println("Classe...:Vendedor");
                System.out.println("Salário..:"+ve.calcularSalario());;
            }

            else if (listaFunc.get(i).getClass().equals(te)) {
                System.out.println("Classe...:Técnico");
                System.out.println("Salário..:"+te.calcularSalario());
            }
}
    
asked by anonymous 12.06.2017 / 00:11

1 answer

2

Use instanceof to check the subtype of the object:

for (int i = 0; i < listaFunc.size(); i++) {

    System.out.println("Classe:"+listaFunc.get(i).getClass().getName().substring(32));
    if (listaFunc.get(i) instanceof Gerente) {
        System.out.println("Classe...:Gerente");
        System.out.println("Salário..:"+ge.calcularSalario());;
    }

    else if(listaFunc.get(i) instanceof Vendedor) {
        System.out.println("Classe...:Vendedor");
        System.out.println("Salário..:"+ve.calcularSalario());;
    }

    else if (listaFunc.get(i) instanceof Tecnico) {
        System.out.println("Classe...:Técnico");
        System.out.println("Salário..:"+te.calcularSalario());
    }
}
    
12.06.2017 / 00:34