2017-04-02 49 views
0

我有兩個類:爲什麼ArrayList中的值在使用反射調用方法後消失?

  1. 子類:接待員類兩種方法ReadDoctorList(字符串的readLine)和DisplayDoctorList()。

  2. 父類:類與ReadLine方法,其中我通過的方法作爲參數,該方法是從類接待員。

我的想法是逐行讀取txt文件,並提取一些行並將它們存儲在ArrayList中。我可以即時打印出價值。 然而,數組列表變爲空如果我從TestClass中調用它。

您的回答將不勝感激!

Output: 
Tonny Bob 
Mike tyson 
The size is: 0 


txt file: 
    Tonny,Bob,abc,abc,D 
    Mike,tyson,abc,abc,D 
    Laura,jack,abc,abc,P 
    Jimmy,viva,abc,abc,P 

public class TestClass { 
    public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ 
     Receptionist obj = new Receptionist(); 
     obj.DisplayDoctorList(); 
     System.out.println("The size is: " + obj.doctorlist.size()); 
    } 

} 

public class Base { 
    String pathusers = "/Users/MacTonish/users.txt"; 
    ArrayList<String> doctorlist = new ArrayList<String>(); 

    public void readLines(Object instance, String path, Method method) 
      throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { 
     try { 
      File txt = new File(path); 
      BufferedReader reader = new BufferedReader(new FileReader(txt)); 
      String readLine = null; 
      while ((readLine = reader.readLine()) != null) { 
       method.invoke(instance, readLine); //something is fishy here. 
      } 
      reader.close(); 
     } catch (

     IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

class Receptionist extends Base { 

    public void DisplayDoctorList() throws NoSuchMethodException, SecurityException, IllegalAccessException, 
      IllegalArgumentException, InvocationTargetException { 
     Method method = Receptionist.class.getMethod("ReadDoctorList", String.class); 
     readLines(new Receptionist(), pathusers, method); 
    } 

    public void ReadDoctorList(String readLine) { 
     String[] token = readLine.split(","); 
     if (token[4].equals("D")) { 
      doctorlist.add(token[0] + " " + token[1]); 
      System.out.println(token[0] + " " + token[1]); //Print out is ok. 
     } 

    } 
} 

回答

2

如果您更改您的接待員的代碼下面,它應該工作

//readLines(new Receptionist(), pathusers, method); 

    //Here you are creating a new object but while printing you are using last created Object of ReceptionList 


變更線的上面的代碼

readLines(this, pathusers, method); 
相關問題