Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set value for one enum?

Tags:

java

enums

I have the following enum:

enum ColumnType {
    TEXT,
    NUMERIC,
    DATE
}

When using this enum, I need to be able to specify a date format String if using the DATE value. How would I do that?

For instance, in my code I want to call a method using something similar to this:

foo(ColumnType.DATE("yyyyMMdd");

Later I would need to be able to retrieve that value using object.getColumnType.getDateFormat() if the ColumnType is DATE. Is this even possible?

The documentation I've been able to find so far suggest ways to set the value of an enum but they all show how to set it for all the enum values, not an individual one.

My understanding of enums is fairly basic so I apologize if this isn't worded correctly. Thanks!

EDIT:

The date format needs to be set at runtime as the user will be selecting/entering the date format string.

like image 477
Zephyr Avatar asked Apr 02 '26 14:04

Zephyr


1 Answers

You can do

enum ColumnType {
    TEXT,
    NUMERIC,
    DATE_YYYYMMDD,
    oher date format
}

However, if you want arbitrary formats you need a class to wrap these

class ColumnTypeFormat {
    ColumnType columnType;
    String format;
}

foo(new ColumnTypeFormat(ColumnType.DATE, "yyyyMMdd"));

You can combine these with a common interface

interface ColumnType {
    String getFormat();
    Class getType();
}

enum SimpleColumnType implements ColumnType {
    TEXT(String.class, "%s"),
    NUMERIC(BigDecimal .class, "%f");

    private Class type;
    private String format;

    SimpleColumnType(Class type, String format) {
        this.type = type;
        this.format = format;
    }

    @Override
    public Class getType() { return type; }

    @Override
    public String getFormat() { return format; }
}

class DateColumnType implements ColumnType {
    private final String format;

    public DateColumnType(String format) {
        this.format = format;
    }

    @Override
    public Class getType() { return LocalDate.class; }

    @Override
    public String getFormat() { return format; }
}

This allows you to have some fixed, pre-created types in the enum but also create additional ones on the fly with a common interface.

like image 179
Peter Lawrey Avatar answered Apr 04 '26 04:04

Peter Lawrey