-6

how can I enforce the compiler to give me an error if the parameter (String Path) that is sent to the constructor can't be a directory?

import java.io.File;
public class Folder {

    protected File file;

    public Folder(String Path){
    file = new File(Path);
    }
}
4

5 回答 5

2

你不能让它成为编译错误(除非你当然重写编译器,即使那样,我认为你不能在编译时确定一个字符串是否是一个有效的目录)。

在 java 中处理这个问题的标准方法是抛出异常,例如:

if (isNotValid(path)) { //condition to be defined
    throw new IllegalArgumentException(path + " is not a valid path");
}
于 2012-12-31T10:36:34.487 回答
0

A compile time error won't be possible.

Yet consider this implementation :

public class Folder {

    private final File folder;

    public Folder(String path) {
        this(new File(path));
    }

    public Folder(File folder) {
        if (!folder.exists() || !folder.isDirectory()) {
            throw new IllegalArgumentException();
        }
        this.folder = folder;
    }

    // add useful methods possibly delegating to contained File object ...
}

This effectively prevents making Folder objects that contain a non directory File. Also note that I've set the folder field private, so no other class can tamper with it.

于 2012-12-31T10:54:04.313 回答
0

可能带有某种注释处理器。

但这是一个非常奇怪的要求。如果它在编译时是一个目录,但不是运行时会发生什么?

于 2012-12-31T10:36:46.980 回答
0

不能是什么目录?在 Windows 中?在 Linux 中?

Java 是跨平台的,每个平台都有自己的规范(例如,在 Windows 中,您不能*在目录名称中使用,但在 Linux 中,您可以......);

我认为您只需要在运行时从方法内部检查File 类的isDirectory()方法。

于 2012-12-31T10:42:24.907 回答
0

您可以通过使用在每个构建上运行的自动单元测试来实现类似的功能。

首先,您需要验证Folder构造函数中的参数,以便Exception在路径无效时抛出 a。

然后你编写单元测试,运行和测试你的所有代码。如果测试失败,BUILD 也会失败——项目的整个打包都会失败。(例如,硬编码的目录不可访问) 这很像编译器错误,构建过程会失败。(确定不一样)

测试确保您测试的代码以所需的方式工作。

当然,如果您使用像 maven 这样的构建工具,这会更容易,单元测试会在每个构建中自动运行。

于 2012-12-31T12:01:07.043 回答