2

Say I have this enum:

public class MyErrors {
    public enum Errors {
        BAD_FILE_PATH("Please point to a valid file");

        private final String message;

        Errors(final String message) {
            this.message = message;
        }

        @Override
        public String toString() {
            return message;
        }
    }

And this call:

Logging.log(Level.INFO, MyErrors.Errors.BAD_FILE_PATH.toString());

It seems so verbose to me to have to call .toString(). Isn't there a way to just call the enum itself and have it return its string by default?

Ideally I'd like something like MyErrors.BAD_FILE_PATH --> which returns a string so it's not so verbose. Does that make any sense?

Aaron
  • 2,154
  • 5
  • 29
  • 42

1 Answers1

1

Both of these work for me in Eclipse:


    LOG.info(Errors.BAD_FILE_PATH);   // Using Log4j
    System.out.println(Errors.BAD_FILE_PATH);

These two methods take an Object parameter. And since are not receiving Strings, the logic in those methods must call the toString() method on the passed in object to obtain a string.

The log() method of java.util.logging.Logger does not support an Object parameter. Instead, it is expecting a String parameter; thus, the logic in this method has no need to call toString().

What you are looking for is a new signature for the Logger that supports an Object parameter. However, I don't know that extending the Logger is a straight forward process or advisable; see here.

Another option would be to use Log4j.

robertf
  • 237
  • 1
  • 11
  • I'm using import java.util.logging.Logger, and using the first signature of (Level level, String message). I get "cannot resolve method 'log'" if I don't have the .toString... so full code looks like LOGGER.log(Level.INFO, ErrorMessages.Errors.STARTED.toString()); – Aaron Nov 17 '17 at 00:25