构造函数参数在类中变为 null,即使它不在 Java 的 main 中

问题描述 投票:0回答:1

如果这是一个愚蠢的问题,我很抱歉,但我对 Java 还很陌生。

这是我的 main.java,我用调试器检查了,selectedFile 不为空

import javax.swing.*;
import javax.swing.filechooser.*;
import java.io.File;

//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {

    public static void main(String[] args) {
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
                "CSV Files", "csv");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {

            File chosenFile = chooser.getSelectedFile();
            // System.out.println(chosenFile.getAbsolutePath());
            if (chosenFile == null) {
                throw new NullPointerException("Null file in main");
            }
            questionAnswersInput inputFile = new questionAnswersInput(chosenFile); // Using a debugger I see that chosenFile is not null.
            System.out.println(inputFile);
        }
    }
}


在这个问题AnswersInput.java类中,inputFile变为null,并且仅在getPath()方法中抛出异常。

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

import javax.swing.*;
import java.io.*;

public class questionAnswersInput {
    final private File inputFile;

    public questionAnswersInput(File inputFile) {
        if (inputFile == null) {
            throw new IllegalArgumentException("Null file in constructor"); // Nothing happens here even tho inputFile is already null
        }
        System.out.println(inputFile.getAbsolutePath()); // This line doesnt execute
        this.inputFile = inputFile;
    }

    private String getPath() {
        System.out.println(inputFile);
        if (this.inputFile == null) {
            System.out.println("Ciao");
            throw new NullPointerException("Null file when getting path"); // This is the exception
        }
        return this.inputFile.getAbsolutePath();
    }

    private String path = getPath();


}


我已经尝试解决这个问题有一段时间了,但我不明白问题出在哪里。预先感谢。

java class constructor
1个回答
1
投票

Java 有一个可怕的怪癖,这确实让学习这门语言的人感到沮丧。创建类时,初始化的顺序如下:

  1. 首先,调用构造函数。
  2. 构造函数中的第一条指令是对超级构造函数的显式或隐式调用,以便调用它。
  3. 一旦 super 的构造函数返回,当前类的每个字段(成员变量)都会被初始化。
  4. 最后,构造函数的其余部分开始运行。

在你的类中,你有一个完全多余的

private String path = getPath();
,这会强制在你的构造函数有机会执行
getPath()
之前调用
this.inputFile = inputFile;
,因此,
inputFile
null
中的
getPath()

要解决此问题,您可以执行以下操作之一:

  • 摆脱

    path
    的字段初始值设定项(将其声明为未初始化),然后从构造函数中显式初始化它,after,您已经意识到了
    inputFile

  • 完全摆脱

    path
    ,并将其替换为对
    getPath()
    的调用。

© www.soinside.com 2019 - 2024. All rights reserved.