Guava Enums
概述
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的更多相关文章
- Guava RateLimiter实现接口API限流
一.简介 Guava提供的RateLimiter可以限制物理或逻辑资源的被访问速率.RateLimit二的原理类似与令牌桶,它主要由许可发出的速率来定义,如果没有额外的配置,许可证将按每秒许可证规定的 ...
- Guava源码阅读-base-Enums
package com.google.common.base; guava源码中对这个类的方法介绍只有一句话: Utility methods for working with {@link Enum ...
- Spring配置cache(concurrentHashMap,guava cache、redis实现)附源码
在应用程序中,数据一般是存在数据库中(磁盘介质),对于某些被频繁访问的数据,如果每次都访问数据库,不仅涉及到网络io,还受到数据库查询的影响:而目前通常会将频繁使用,并且不经常改变的数据放入缓存中,从 ...
- Spring cache简单使用guava cache
Spring cache简单使用 前言 spring有一套和各种缓存的集成方式.类似于sl4j,你可以选择log框架实现,也一样可以实现缓存实现,比如ehcache,guava cache. [TOC ...
- Guava库介绍之实用工具类
作者:Jack47 转载请保留作者和原文出处 欢迎关注我的微信公众账号程序员杰克,两边的文章会同步,也可以添加我的RSS订阅源. 本文是我写的Google开源的Java编程库Guava系列之一,主要介 ...
- Google Java编程库Guava介绍
本系列想介绍下Java下开源的优秀编程库--Guava[ˈgwɑːvə].它包含了Google在Java项目中使用一些核心库,包含集合(Collections),缓存(Caching),并发编程库(C ...
- [Java 缓存] Java Cache之 Guava Cache的简单应用.
前言 今天第一次使用MarkDown的形式发博客. 准备记录一下自己对Guava Cache的认识及项目中的实际使用经验. 一: 什么是Guava Guava工程包含了若干被Google的 Java项 ...
- [转载]Google Guava官方教程(中文版)
原文链接 译文链接 译者: 沈义扬,罗立树,何一昕,武祖 校对:方腾飞 引言 Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] ...
- java开发人员,最应该学习和熟练使用的工具类。google guava.(谷歌 瓜娃)
学习参考文章: http://blog.csdn.net/wisgood/article/details/13297535 http://ifeve.com/google-guava/ http:// ...
随机推荐
- 将 Ubuntu 16.04 LTS 升级到 Ubuntu 18.04 LTS
将 Ubuntu 16.04 LTS 升级到 Ubuntu 18.04 LTS Ubuntu 18.04 LTS(Bionic Beaver)即将发布, 如果您正在使用Ubuntu 16.04LT ...
- 让HTML5来为你定位(转)
add by zhj: HTML5的地理定位返回的应该都是GPS坐标,即WGS-84坐标,参见Map Types - Google Maps JavaScript API v3 本文使用的是Chrom ...
- Python 项目实践三(Web应用程序) 第三篇
接着上节的继续学习,现在要显示所有主题的页面 有了高效的网页创建方法,就能专注于另外两个网页了:显示全部主题的网页以及显示特定主题中条目的网页.所有主题页面显示用户创建的所有主题,它是第一个需要使用数 ...
- faker php测试数据库生成
官方地址:https://github.com/fzaninotto/Faker 使用方式: 1.composer直接下载: composer require fzaninotto/faker 2.将 ...
- Educational Codeforces Round 14 C. Exponential notation 数字转科学计数法
C. Exponential notation 题目连接: http://www.codeforces.com/contest/691/problem/C Description You are gi ...
- SGU 275. To xor or not to xor (高斯消元法)
题目链接:http://acm.sgu.ru/problem.php?contest=0&problem=275 题意:给你n个数,可以选择任意个数异或,但是要使得最后的异或值最大. 我们把每 ...
- Android app开发中用户协议(使用条款)文字自己主动换行
用户协议(使用条款)文字自己主动换行处理 转载请注明出处:http://blog.csdn.net/u012301841/article/details/46648821 我们在开发app的时候.常常 ...
- JVM菜鸟进阶高手之路
http://www.jianshu.com/u/3def157aab07?utm_medium=note-author-link&utm_source=mobile
- Python yield使用
https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/ 您可能听说过,带有 yield 的函数在 Python 中被称 ...
- TMS WEB CORE直接从HTML&CSS设计的页面布局
TMS WEB CORE直接从HTML&CSS设计的页面布局 TMS WEB CORE支持DELPHI IDE中拖放控件,生成HTML UI.这种方式适合DELPHI和C++ BUILDER的 ...