一、Enum使用(1.5使用)
enum在Jdk1.5就已经引入了,在Hmily中很多地方都可以看到它的身影。在日常开发中enum可以替换很多常量,更符合面向对象的观念。记录下它的用法:
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.hmily.tcc.common.enums;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
/**
* The enum Blocking queue type enum.
*
* @author xiaoyu
*/
public enum BlockingQueueTypeEnum {
/**
* Linked blocking queue blocking queue type enum.
*/
LINKED_BLOCKING_QUEUE("Linked"),
/**
* Array blocking queue blocking queue type enum.
*/
ARRAY_BLOCKING_QUEUE("Array"),
/**
* Synchronous queue blocking queue type enum.
*/
SYNCHRONOUS_QUEUE("SynchronousQueue");
private String value;
BlockingQueueTypeEnum(final String value) {
this.value = value;
}
/**
* Gets value.
*
* @return the value
*/
public String getValue() {
return value;
}
/**
* From string blocking queue type enum.
*
* @param value the value
* @return the blocking queue type enum
*/
public static BlockingQueueTypeEnum fromString(final String value) {
Optional<BlockingQueueTypeEnum> blockingQueueTypeEnum =
Arrays.stream(BlockingQueueTypeEnum.values())
.filter(v -> Objects.equals(v.getValue(), value))
.findFirst();
return blockingQueueTypeEnum.orElse(BlockingQueueTypeEnum.LINKED_BLOCKING_QUEUE);
}
@Override
public String toString() {
return value;
}
}
这个Enum非常有代表性,它定义了BlockingQueue的四种类型,需要注意的一点如果Enum有有参构造器,那么它一定为private,并且可以在枚举类中添加自己的方法,如本例子的fromString(lambda表达式写法->转换为下的非lambda写法)。
public static BlockingQueueTypeEnum fromString(final String value)
{
for(BlockingQueueTypeEnum blockingQueueTypeEnum:BlockingQueueTypeEnum.values())
{
if(StringUtils.equals(blockingQueueTypeEnum.getValue(),value))
{
return blockingQueueTypeEnum;
}
}
return BlockingQueueTypeEnum.LINKED_BLOCKING_QUEUE;
}