gpt4 book ai didi

java - 为什么使用反射调用方法后ArrayList中的值消失了?

转载 作者:行者123 更新时间:2023-12-02 02:55:26 25 4
gpt4 key购买 nike

我有两门课:

  1. 子类:接待员类,具有两个方法 ReadDoctorList(String 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.
}

}
}

最佳答案

如果您对接待员代码进行以下更改,它应该可以工作

    //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);

关于java - 为什么使用反射调用方法后ArrayList中的值消失了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43164245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com