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

时间:2016-08-30 13:52:08

标签: java arraylist netbeans polymorphism

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

 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
    } 
}

1 个答案:

答案 0 :(得分:2)

您可以使用The Reflection API执行此操作。 例如:

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

根据this文章选择最适合您的方式。