概述

Enums提供了几个操作Enum的便利方法

常用方法

Field getField(Enum<?> enumValue): 返回变量名为enumValue变量值的Field

<T extends Enum<T>> Function<String, T> valueOfFunction(Class<T> enumClass): 返回一个可以将enum名字字符串转换成指定类型的enum的, 如果enum不存在时,Function将返回null

Optional<T> getIfPresent(Class<T> enumClass, String value): 使用Enum.valueOf()来返回指定名称和class的Enum的Optional,如果不存在则返回Absent, 常见用法Enums.getIfPresent(Country.class, countryInput).or(Country.DEFAULT)

示例代码

        TestEnum a = TestEnum.A;
System.out.println(Enums.getField(a));
Function<String, TestEnum> function = Enums.valueOfFunction(TestEnum.class);
System.out.println(function.apply("B"));
System.out.println(Enums.getIfPresent(TestEnum.class, "D").or(TestEnum.A)); // D不存在,则返回默认的A
System.out.println(Enums.getIfPresent(TestEnum.class, "C").or(TestEnum.A)); // C存在,直接返回

public static final enumtest.TestEnum enumtest.TestEnum.A
B
A
C

源代码

/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible; import java.io.Serializable;
import java.lang.reflect.Field; import javax.annotation.Nullable; /**
* Utility methods for working with {@link Enum} instances.
*
* @author Steve McKay
*
* @since 9.0
*/
@GwtCompatible(emulated = true)
@Beta
public final class Enums { private Enums() {} /**
* Returns the {@link Field} in which {@code enumValue} is defined.
* For example, to get the {@code Description} annotation on the {@code GOLF}
* constant of enum {@code Sport}, use
* {@code Enums.getField(Sport.GOLF).getAnnotation(Description.class)}.
*
* 返回变量名为enumValue变量值得Field
*
* @since 12.0
*/
@GwtIncompatible("reflection")
public static Field getField(Enum<?> enumValue) {
Class<?> clazz = enumValue.getDeclaringClass();
try {
return clazz.getDeclaredField(enumValue.name());
} catch (NoSuchFieldException impossible) {
throw new AssertionError(impossible);
}
} /**
* Returns a {@link Function} that maps an {@link Enum} name to the associated
* {@code Enum} constant. The {@code Function} will return {@code null} if the
* {@code Enum} constant does not exist.
*
* 返回一个可以将enum名字字符串转换成指定类型的enum的Function
* 如果enum不存在时,Function将返回null
*
* @param enumClass the {@link Class} of the {@code Enum} declaring the
* constant values.
*/
public static <T extends Enum<T>> Function<String, T> valueOfFunction(Class<T> enumClass) {
return new ValueOfFunction<T>(enumClass);
} /**
* A {@link Function} that maps an {@link Enum} name to the associated
* constant, or {@code null} if the constant does not exist.
*/
private static final class ValueOfFunction<T extends Enum<T>>
implements Function<String, T>, Serializable { private final Class<T> enumClass; private ValueOfFunction(Class<T> enumClass) {
this.enumClass = checkNotNull(enumClass);
} @Override
public T apply(String value) {
try {
// 通过valueOf方法实现将value转为enum
return Enum.valueOf(enumClass, value);
} catch (IllegalArgumentException e) {
return null;
}
} @Override public boolean equals(@Nullable Object obj) {
return obj instanceof ValueOfFunction &&
enumClass.equals(((ValueOfFunction) obj).enumClass);
} @Override public int hashCode() {
return enumClass.hashCode();
} @Override public String toString() {
return "Enums.valueOf(" + enumClass + ")";
} private static final long serialVersionUID = 0;
} /**
* Returns an optional enum constant for the given type, using {@link Enum#valueOf}. If the
* constant does not exist, {@link Optional#absent} is returned. A common use case is for parsing
* user input or falling back to a default enum constant. For example,
* {@code Enums.getIfPresent(Country.class, countryInput).or(Country.DEFAULT);}
*
* 使用Enum.valueOf()来返回指定名称和class的Enum的Optional,如果不存在则返回Absent
*
* @since 12.0
*/
public static <T extends Enum<T>> Optional<T> getIfPresent(Class<T> enumClass, String value) {
checkNotNull(enumClass);
checkNotNull(value);
try {
return Optional.of(Enum.valueOf(enumClass, value));
} catch (IllegalArgumentException iae) {
return Optional.absent();
}
}
}

Guava Enums的更多相关文章

  1. Guava RateLimiter实现接口API限流

    一.简介 Guava提供的RateLimiter可以限制物理或逻辑资源的被访问速率.RateLimit二的原理类似与令牌桶,它主要由许可发出的速率来定义,如果没有额外的配置,许可证将按每秒许可证规定的 ...

  2. Guava源码阅读-base-Enums

    package com.google.common.base; guava源码中对这个类的方法介绍只有一句话: Utility methods for working with {@link Enum ...

  3. Spring配置cache(concurrentHashMap,guava cache、redis实现)附源码

    在应用程序中,数据一般是存在数据库中(磁盘介质),对于某些被频繁访问的数据,如果每次都访问数据库,不仅涉及到网络io,还受到数据库查询的影响:而目前通常会将频繁使用,并且不经常改变的数据放入缓存中,从 ...

  4. Spring cache简单使用guava cache

    Spring cache简单使用 前言 spring有一套和各种缓存的集成方式.类似于sl4j,你可以选择log框架实现,也一样可以实现缓存实现,比如ehcache,guava cache. [TOC ...

  5. Guava库介绍之实用工具类

    作者:Jack47 转载请保留作者和原文出处 欢迎关注我的微信公众账号程序员杰克,两边的文章会同步,也可以添加我的RSS订阅源. 本文是我写的Google开源的Java编程库Guava系列之一,主要介 ...

  6. Google Java编程库Guava介绍

    本系列想介绍下Java下开源的优秀编程库--Guava[ˈgwɑːvə].它包含了Google在Java项目中使用一些核心库,包含集合(Collections),缓存(Caching),并发编程库(C ...

  7. [Java 缓存] Java Cache之 Guava Cache的简单应用.

    前言 今天第一次使用MarkDown的形式发博客. 准备记录一下自己对Guava Cache的认识及项目中的实际使用经验. 一: 什么是Guava Guava工程包含了若干被Google的 Java项 ...

  8. [转载]Google Guava官方教程(中文版)

      原文链接  译文链接 译者: 沈义扬,罗立树,何一昕,武祖  校对:方腾飞 引言 Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] ...

  9. java开发人员,最应该学习和熟练使用的工具类。google guava.(谷歌 瓜娃)

    学习参考文章: http://blog.csdn.net/wisgood/article/details/13297535 http://ifeve.com/google-guava/ http:// ...

随机推荐

  1. 格式化输出函数:printf 那些事 (C语言)

    printf函数提供格式化输出转换 函数包含在头文件  <stdio.h>  中 #include <stdio.h> ...... 函数的原型在头文件的声明为 _CRTIMP ...

  2. DSP 程序的执行时间

    在访问TSCL寄存器前要定义 cregister volatile unsigned int TSCL; TSCL/TSCH,它们与CPU同频,共同表示一个64-bit数,CPU运行一个cycle,该 ...

  3. Ubuntu16.04 14.04 配置caffe(CPU only)

    1.安装依赖 sudo apt-get install libprotobuf-dev libleveldb-dev libsnappy-dev libopencv-dev libhdf5-seria ...

  4. 005.基于docker部署etcd集群部署

    一 环境准备 ntp配置:略 #建议配置ntp服务,保证时间一致性 etcd版本:v3.3.9 防火墙及SELinux:关闭防火墙和SELinux 名称 地址 主机名 备注 etcd1 172.24. ...

  5. JSONObject 自定义过滤配置

    一.自定义过滤器说明 PropertyPreFilter 根据PropertyName判断是否序列化  PropertyFilter 根据PropertyName和PropertyValue来判断是否 ...

  6. 【翻译】What is State Machine Diagram(什么是状态机图)?

    [翻译]What is State Machine Diagram(什么是状态机图)? 写在前面 在上一篇学习类图的时候将这个网站上的类图的一篇文章翻译了出来,感觉受益良多,今天来学习UML状态机图, ...

  7. Android- SharedPreferences 使用详解

    Android-SharedPreferences 使用详解 参考 https://developer.android.google.cn/reference/android/content/Shar ...

  8. NOI.AC NOIP模拟赛 第一场 补记

    NOI.AC NOIP模拟赛 第一场 补记 candy 题目大意: 有两个超市,每个超市有\(n(n\le10^5)\)个糖,每个糖\(W\)元.每颗糖有一个愉悦度,其中,第一家商店中的第\(i\)颗 ...

  9. Codeforces Round #368 (Div. 2) D. Persistent Bookcase 离线 暴力

    D. Persistent Bookcase 题目连接: http://www.codeforces.com/contest/707/problem/D Description Recently in ...

  10. 接口开发-集成数据库操作(mybatis)

    关于数据存储,最常用的方式就是存到数据库,此篇以MySQL数据库为例,以mybatis框架完成数据库的操作. 一.添加对应依赖 <!-- 数据库:MySQL --> <depende ...