[英]How can I access to a public final static list declared into an utility class from another class in a Java application?
[英]How can I access this list in another class?
我已经从 CSV 文件创建了一个项目列表,但不确定如何在另一个类中访问此列表。 我已经在新类中创建了列表类的实例,但是一直找不到访问列表的方法。
public class ListClass {
public static void main(String[] args) throws IOException {
CSVReader csvReader = new CSVReader();
List list = csvReader.Read("csvFile.csv");
}
}
我已经能够打印列表,所以我知道它肯定有效,但我不确定如何在另一个类中访问它。 除了以下内容之外,新类目前是空的;
ListClass listClass = new ListClass();
您应该将列表作为私有实例变量存储在 ListClass 中并为其创建一个 getter:
public class ListClass {
private List list = null;
public static void main(String[] args) {
try {
new ListClass();
} catch(IOException ioEx){
// error handling
}
}
public ListClass() throws IOException {
CSVReader csvReader = new CSVReader();
list = csvReader.Read("csvFile.csv");
}
public List getList(){
return list;
}
}
然后你可以从你的其他班级访问它:
try {
ListClass listClass = new ListClass();
List list = listClass.getList();
} catch(IOException ioEx){
// error handling
}
您需要通过执行以下操作之一使其他类可以访问该列表:
class ListClass {
public List csvList;
...
}
class ListClass {
private List csvList;
public List getCsvList() {
return this.csvList;
}
...
}
还有很多其他方法可以访问类变量。 第二种是一种非常常见的做法。
1 ) 将您的列表添加为 ListClass 的字段并将您的初始化放在构造函数中。
public class ListClass {
public List list;
ListClass(){
try{
CSVReader csvReader = new CSVReader();
list = csvReader.Read("csvFile.csv");
}catch(IOException e){
//handle the exception
}
}
}
2)在OtherClass中创建ListClass的对象。
public class OtherClass{
public static void main(String[] args){
ListClass listClass = new ListClass();
List newList = listClass.list;// your list
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.