Skip to content

Instantly share code, notes, and snippets.

@ctranxuan
Created May 19, 2017 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctranxuan/b03b9096fbc25da4135c41a5e36fed4e to your computer and use it in GitHub Desktop.
Save ctranxuan/b03b9096fbc25da4135c41a5e36fed4e to your computer and use it in GitHub Desktop.
Some Java HowTos

Enum reverse lookup pattern

import com.google.common.collect.ImmutableMap;

import java.io.File;
import java.util.Map;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * @author ctranxuan.
 */
public enum Format {
    PDF {
        @Override
        public void formatFile(File file) {
            System.out.println("PDF format");
        }
    }, EXCEL {
        @Override
        public void formatFile(File file) {
            System.out.println("Excel format");
        }
    }, CSV {
        @Override
        public void formatFile(File file) {
            System.out.println("CSV format");
        }
    };
     
    private static final Map<String, Format> LOOKUP = 
            ImmutableMap.of("pdf", PDF,
                            "excel", EXCEL,
                            "csv", CSV);
     
     
    public static Format from(String aInput) {
        return checkNotNull(LOOKUP.get(aInput), "Not a valid format %s", aInput);
    }
     
    public abstract void formatFile(File file);

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment