1

我想为枚举构造函数创建一个 Path 实例:

/** Temporary paths. */
public enum PATHS {

    /** First temporary directory. */
    PATH1(Files.createTempDirectory(new StringBuilder("tnk").append(File.separator).append("path1")
            .toString())),
    /** Second temporary directory. */
    PATH2(Files.createTempDirectory(new StringBuilder("tnk").append(File.separator).append("path2")
            .toString()));

    /** {@link Path} reference. */
    final Path mPath;

    /**
     * Constructor.
     * 
     * @param pPath
     *            {@link Path} reference
     */
    PATHS(final Path pPath) {
        mPath = pPath;
    }

    /**
     * Get {@link File} associated with the path.
     * 
     * @return {@link File} reference
     */
    public File getFile() {
        return mPath.toFile();
    }
}

Files.createTempDirectory(String, FilleAttribute<?> atts)抛出检查异常(IOException),但我如何捕获或抛出异常,或者更准确地说,我如何处理异常?似乎是一个转储问题,但我现在不知道。

4

2 回答 2

2

而是在构造函数中处理它。

PATH1("path1"),
PATH2("path2");

final Path mPath;

PATHS(final String path) {
    try {
        mPath = Files.createTempDirectory(new StringBuilder("tnk").append(File.separator).append(path).toString());
    } catch (IOException e) {
        throw new ExceptionInInitializerError(e);
    }
}

额外的好处是它还可以最大限度地减少这种特殊情况下的代码重复。

话虽如此,对于汤姆·霍廷(Tom Hawtin)试图告诉您的内容,我真的会三思而后行。

于 2011-11-17T19:54:16.080 回答
0

真的任何接触状态都不应该用静态字段来完成。所以简单地使“PATHS”成为一个普通的类。创建一次,并将其赋予应该使用它的对象。更好的设计应该改进错误处理、测试、依赖性、安全性等。

于 2011-11-17T19:41:29.407 回答