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:// ...
随机推荐
- 9-2 The Tower of Babylon uva437 (DP)
题意:有n种立方体 每种都有无穷多个 要求选一些立方体叠成一根尽量高的柱子 (可以自行选择哪条边为高 )使得每个立方体的底面都严格小于他下方的立方体 为DAG模型 在任何时候 只有顶面的尺寸会影响到 ...
- Wannafly 挑战赛 19 参考题解
这一次的 Wannafly 挑战赛题目是我出的,除了第一题,剩余的题目好像对大部分算法竞赛者来说好像都不是特别友好,但是个人感觉题目质量还是过得去的,下面是题目链接以及题解. [题目链接] Wanna ...
- python基础下的数据结构与算法之链表
一.链表的定义 用链接关系显式表示元素之间顺序关系的线性表称为链接表或链表. 二.单链表的python实现 class Node(object): """定义节点&quo ...
- js冲刺一下
js中__proto__和prototype的区别和关系 1.对象有属性__proto__,指向该对象的构造函数的原型对象. 2.方法除了有属性__proto__,还有属性prototype,prot ...
- Redis介绍及部署在CentOS7上(一)
0.Redis目录结构 1)Redis介绍及部署在CentOS7上(一) 2)Redis指令与数据结构(二) 3)Redis客户端连接以及持久化数据(三) 4)Redis高可用之主从复制实践(四) 5 ...
- Chart.js Y轴数据以百分比展示
新手一枚,解决的问题喜欢记录,也许正好有人在网上迷茫的百度着.-0- 最近使用Chart.js做折线图的报表展示,直接显示整数啥的很好弄毕竟例子直接在哪里可以用,百分比就没办法了.百度慢慢汲取营养,虽 ...
- 系统的Drawable(二)-Selector
系统的Drawable(二)-Selector Selector漫谈 Selector是定义 StateListDrawable 的标签,该Drawable代表着一个Drawable的集合,每一个Dr ...
- 1295 N皇后问题
题目描述 Description 在n×n格的棋盘上放置彼此不受攻击的n个皇后.按照国际象棋的规则,皇后可以攻击与之处在同一行或同一列或同一斜线上的棋子.n后问题等价于再n×n的棋盘上放置n个皇后,任 ...
- Western Subregional of NEERC, Minsk, Wednesday, November 4, 2015 Problem G. k-palindrome dp
Problem G. k-palindrome 题目连接: http://opentrains.snarknews.info/~ejudge/team.cgi?SID=c75360ed7f2c7022 ...
- 允许mysql远程用户连接。
默认mysql是禁止远程用户连接的.连接提示: 1045,“Access denied for user 'root'@'192.168.100.1' (using password:YES)&quo ...