Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Special Characters in Java Enums

Currently attempting to have special characters, primarily '.' a number, however, it seems enums require letters only. Is there a way to use special characters? Currently trying to make a file saver and many file types have numbers in them, an example being:

public enum FileType {

    7z(".7z"),
    ace(".ace"),
    apk(".apk"),
    bz2(".bz2"),
    crx(".crx"),
    dd(".dd"),
    deb(".deb"),
    gz(".gz"),
    gzip(".gzip"),
    jar(".jar"),
    rar(".rar"),
    rpm(".rpm"),
    sit(".sit"),
    sitx(".sitx"),
    snb(".snb"),
    tar(".tar"),
    tar.gz(".tar.gz"),
    tqz(".tqz"),
    zip(".zip"),
    zipx(".zipx");

    public final String FILESUFFIX;

    FileType(String FileSuffix) {
        this.FILESUFFIX = FileSuffix;
    }

    public String getSuffix() {
        return FILESUFFIX;
    }
}

I have looked throughout StackOverflow, however, I haven't found a way that suited me. I do not understand how to do 'maps' or the other fancy stuff, so is there an alternate way to simple get something like mp4 to be an Enum?

like image 699
Connor Avatar asked Jun 04 '26 21:06

Connor


2 Answers

this value declared in the enum 7z is invalid same as you can not declare a variable with the name 7z since that will be an invalid java identifier https://docs.oracle.com/cd/E19798-01/821-1841/bnbuk/index.html

alternative to that you can play with underscores,and something better is use UPPER_CASE

public enum FileType {

    _7Z(".7z"),
    _ACE(".ace"),
    _APK(".apk"),
    _BZ2(".bz2"),
    _CRX(".crx"),
    etc etc
like image 87
ΦXocę 웃 Пepeúpa ツ Avatar answered Jun 07 '26 12:06

ΦXocę 웃 Пepeúpa ツ


Enum identifiers follow the same rules as other Java identifiers:

The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign) and ‘_‘ (underscore).

Identifiers should not start with digits([0-9]). For example “123geeks” is a not a valid java identifier.

Java identifiers are case-sensitive

From your example, mp4 is a valid identifier, but 7z is not (because it starts with a number)

Note: by convention, enum identifiers are typically all uppercase.

like image 28
Krease Avatar answered Jun 07 '26 11:06

Krease