Question

I'd like to create a Path instance for an enum constructor:

/** 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)throws a checked exception (IOException) but how do I catch or throw the exception or more precisely how do I handle the exception? Seems to be a dump question, but I have no idea right now.

Was it helpful?

Solution

Handle it in the constructor instead.

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);
    }
}

Additional benefit is that it also minimizes code duplication in this particular case.

Said that, I'd really think twice about what Tom Hawtin is trying to tell you.

OTHER TIPS

Really anything touching state should not be done with static fields. So simply makes "PATHS" a normal class. Create it once, and endow it to objects that should be using it. The better design should improve error handling, testing, dependency, security, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top