如何从java中的抽象类arraylist中打印特定的对象类型

How to print a specific object type from an abstract class arraylist in java

下面的课是我的主课。我的arraylist是"Employee"的类型,该arraylist包含许多具有多个对象(多态性)的元素。所以我想知道,当用户输入类名时,我应该从arraylist中打印出特定类的雇员。例如,当用户输入"外科医生"时,程序应该能够从数组列表中打印出所有外科医生员工的。请帮忙,提前谢谢。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
 import java.util.*;


public class HospitalDatabase {

    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        String q;
        String w;
        ArrayList<Employee> e = new ArrayList<Employee>();
        Employee s = new Surgeon("Christian Barnard", 2113211,"Cardiac","Cardiology",
                2000,"Yale University");
        Employee i = new ITSupport("Mickey Mouse", 11280, Department.IT, 26,"Mac OS");
        Employee n = new Nurse("Florence Nightingale", 54678,"Urgent Care",
               "Emergency", false, HospitalWing.North);
        Employee p = new PatientAccountsManager("Donald Duck", 32465, Department.PatientSupport,
                99, true);
        Employee s1 = new Surgeon("Sanjay Gupta", 42171,"Neurosurgery",
               "Neurology", 500,"Duke University");
        Employee n1 = new Nurse("Mary Breckinridge", 56536,"Gynecology","Midwife",
                true, HospitalWing.West);


        e.add(s);
        e.add(i);
        e.add(n);
        e.add(p);
        e.add(s1);
        e.add(n1);

        System.out.println(e.toString());
        System.out.println(Employee.numEmployees);
        System.out.println("-------------******--------------");

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a name:");
        q = scan.nextLine();
        boolean j = false;
        System.out.println("***************");

        for(Employee v: e){
            if(v.name.contains(q)){
                System.out.println(v.name);
                j = true;
            }
        }
        if(j == false){
            System.out.println("Name not found");
        }  
        System.out.println("----------------**************---------------");

        Scanner f = new Scanner(System.in);
        System.out.println("Enter the class of employees:");
        w = f.nextLine();
        System.out.println("***************************");

        //PLEASE SHOW THE CODE HERE
    }
}


您可以使用反射API来执行此操作。例如:

1
2
3
String className1 = e.getClass().getSimpleName();
String className2 = e.getClass().getName();
String className3 = e.getClass().getCanonicalName();

考虑到这篇文章,选择一个最适合你的。