我已将值分配给Report Info类的成员,并尝试添加到Report Group类。获取java null指针异常。即使我已经在一开始就初始化了报告Info。
执行此操作时出错 - reportGroup.getReportList()。add(reportInfo);
我有两个java类。
ReportGroup.java
String GroupName;
List<ReportInfo>reportList;
public String getReportGroupName() {
return ReportGroupName;
}
public void setReportGroupName(String reportGroupName) {
ReportGroupName = reportGroupName;
}
public List<ReportInfo> getReportList() {
return reportList;
}
public void setReportList(List<ReportInfo> reportList) {
this.reportList = reportList;
}
}
ReportInfo.java
String ReportName;
String ReportId;
String ReportPath;
//Getter and Setter
主要课程:
public class test {
List<ReportInfo> reportInfo = new ArrayList<ReportInfo>();
public static void main(String[] args) throws IOException {
String orgId="346";
String orgName="Ralph Lauren Corporation";
String reportPath= "/"+orgId +"_"+orgName.replaceAll(" ","_");
String reportFolderPath = "C:/Lokesh/Dev Tools/apache-tomcat-6.0.37/webapps/ROOT/Reports";
List<String> filesArray = null;
filesArray = new ArrayList<String>();
String filetowrite="C:/Users/lbandhu/Desktop/test.html";
FileWriter fw=new FileWriter(filetowrite);
ReportGroup reportGroup=new ReportGroup();
reportGroup.setReportGroupName(orgName); //Organization Name such as Ralph Lauren Corporation
fw.write("<html><head><title>"+ reportGroup.ReportGroupName+"</title><h1>Utilization Report</h1><span>Please contact your account manager for a listing of utilization report definitions or with any questions on your organization’s reports. </span><br></head><body><table>");
//fw.write("<br><h>"+orgName+"</h><br>");
File folder = new File(reportFolderPath+reportPath);
List<String> reportNames = listFolder(folder);
for (String rname : reportNames) {
ReportInfo reportInfo=new ReportInfo();
reportInfo.setReportName(rname);
folder = new File(reportFolderPath+reportPath+"/"+reportInfo.ReportName);
System.out.println(folder);
fw.write("<br><tr> "+reportInfo.ReportName +" Utilization Reports</tr><br>"); //Report Name such as Monthly,Quarterly and Yearly
Iterator<String> iterator=listFilesForFolder(folder, filesArray).iterator();
writeReportPath( fw,iterator, reportFolderPath,reportInfo);
fw.write("<br>");
reportGroup.getReportList().add(reportInfo);
}
filesArray.clear();
fw.close();
}
答案 0 :(得分:3)
您需要在构造函数中初始化列表:
public ReportGroup(){
reportList = new ArrayList<ReportInfo>();
}
或
public ReportGroup(String GroupName){
this.GroupName = GroupName;
reportList = new ArrayList<ReportInfo>();
}
答案 1 :(得分:2)
您正在初始化reportInfo
课程的test
个字段,而不是reportInfo
的字段ReportGroup
。看起来你实际上并不是你的test
类,并且这个字段对于静态(即类)方法是不可见的。即使它是可见的(例如,如果它本身是静态的),你也会用局部变量reportInfo
来遮蔽它。
当您在ReportInfo reportInfo = new ReportInfo()
循环的第一行中for
时,您正在创建一个新的ReportGroup
,其中包含一个未初始化的新reportInfo
成员。
您的ReportGroup
应该是这样的:
class ReportGroup {
final List<ReportInfo> reportInfo = new ArrayList<>();
}
或者,您可以在构造函数中进行初始化:
class ReportGroup {
final List<ReportInfo> reportInfo;
ReportGroup () {
reportInfo = new ArrayList<ReportInfo>;
}
}