简体   繁体   中英

Java enum declaration contains members and methods

I came across the following bit of Java code in some open source code shown below (older version of JSoup).

There's a class declaration. And within the class declaration is an enum declared. But the enum appears to be more of a class like declaration with a constructor method, private members, and a public method. The actual enum values declared are getting initialized with a static member of the parent class.

I'm used to vanilla enum declarations, but I haven't seen this syntax or pattern before.

What do you call this pattern, how does it work, and what does it enable?

public class Entities {
    public enum EscapeMode {
        /** Restricted entities suitable for XHTML output: lt, gt, amp, and quot only. */
        xhtml(xhtmlByVal),
        /** Default HTML output entities. */
        base(baseByVal),
        /** Complete HTML entities. */
        extended(fullByVal);

        private Map<Character, String> map;

        EscapeMode(Map<Character, String> map) {
            this.map = map;
        }

        public Map<Character, String> getMap() {
            return map;
        }
    }

    private static final Map<String, Character> full;
    private static final Map<Character, String> xhtmlByVal;
    private static final Map<String, Character> base;
    private static final Map<Character, String> baseByVal;
    private static final Map<Character, String> fullByVal;

    private Entities() {}

    // remaining code not shown for brevity

Enums in Java are just classes, a special kind of class, but still a class.

So, yes, enums can have constructors, member fields, and methods.

Technically, all Java enums are implicitly a subclass of the java.lang.Enum class. This is why an enum cannot extend from a class of your choosing; enums already extend from Enum .

See tutorial by Oracle on enums.

By the way, Java 16 brought a handy new feature for enums: You can declare an enum locally . As part of the work to implement records , we can now declare enums, interfaces, and records locally.

enum in Java is just a class with constants of its type. This means an enum A will contain constants of type A.

This enum EscapeMode has a private data member map and a constructor is made to initialize map . The getter getMap() returns the map .

xhtml , base , and extended are constants separated by a comma and terminated with a semicolon. As they are objects of EscapeMode , you need to pass a Map object to the constructor to initialize them. xhtmlByVal is passed to the constructor to initialize xhtml , and so on.

This feature brings properties and behaviors to enum objects. Enums are just like any other class but inherit the java.lang.Enu m class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM