3

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?

9
  • 2
    How about "" + MyErrors.Errors.BAD_FILE_PATH? Commented Nov 16, 2017 at 20:58
  • 8
    Sure. Don't use an enum. Provide, instead, a static final String. Commented Nov 16, 2017 at 20:58
  • 1
    First time I have ever heard of calling toString is considered verbose Commented Nov 16, 2017 at 21:01
  • Why are you trying to use an enum for something that clearly isn't? Commented Nov 16, 2017 at 21:01
  • 2
    @Dummy actually calling toString is verbose, I don't remember doing so over the past few years: if you want to print an object you can simply print the object (which will implicitly call its toString method). Commented Nov 16, 2017 at 21:06

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.