JAVA通用性的枚举类遍历实现

前言

好久没有登录CSDN了,上一次发文章居然是去年9月份l|ू・ω・` ),以后要多发点文章,记录并分享一下工作与生活,手动分割线l( ̄ェ ̄;)

通用性的枚举类遍历产出背景

我们公司系统中有许多类似状态这样的数据库字段(下图为其中之一)在这里插入图片描述
页面需要展示如下:
字段页面展示

解决方法

1.方法一 简单粗暴如下:

					<select >
					 	<option value="-1">全部</option>
					 	<option value="1">处理中</option>
					 	<option value="2">处理成功</option>
					 	<option value="3">处理失败</option>
					 	<option value="7">超时未支付</option>
					 </select>

但是这种方法可维护行极差,稍有变动需要每个页面手动修改(累死)

2.方法二 同事A用的方法,在后端定义好类型再以json传到前端组装

public class PayStatus {
	private List<HashMap<Integer, String>> listType = new ArrayList<HashMap<Integer, String>>();
	public List<HashMap<Integer, String>> getlistType() {
	
		HashMap<Integer, String> map1 = new HashMap<Integer, String>();
		map1.put(1, "处理中");
		listType.add(map1);
		
		HashMap<Integer, String> map2 = new HashMap<Integer, String>();
		map2.put(2, "处理成功");
		listType.add(map2);
		
		HashMap<Integer, String> map3 = new HashMap<Integer, String>();
		map3.put(3, "处理失败");
		listType.add(map3);
		
		HashMap<Integer, String> map7 = new HashMap<Integer, String>();
		map7.put(7, "超时未支付");
		listType.add(map7);
		
		return listType;
	}
}

这个方法明显比第一个好多了,但是我不喜欢|ू・ω・` ),感觉太累赘了(数据库里那么多的类型字段,得new多少HashMap呀)
3.同事B的用的方法,也是在后端定义好类型再以json传到前端组装

public enum PayStatusEnum {
	status1(1, "处理中"), 
	status2(2, "处理成功"), 
	status3(3, "处理失败"),
	status7(7, "超时未支付");
	private final int key;
	private final String value;

	private TraderEnum(int key, String value) {
		this.key = key;
		this.value = value;
	}

	public static Map<Integer,String> getMap(){
		Map<Integer,String>  map = new HashMap<>();
		for (TraderEnum temp : TraderEnum.values()) {
			map.put(temp.getKey(),temp.getValue());
		}
		return map;
	}
	
	public int getKey() {
		return key;
	}

	public String getValue() {
		return value;
	}	
}

这个方法看起来舒服多了,但是每个枚举类里都要手写一个getMap方法
4.一个CSDN上大佬的写法,直接上反射机制
JAVA枚举操作(获取值,转map集合)
可以说非常强了,但是本着能不用反射就不用的原则我还是选择自己写一个不用反射机制的

反射的用途 Uses of Reflection
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.
反射被广泛地用于那些需要在运行时检测或修改程序行为的程序中。这是一个相对高级的特性,只有那些语言基础非常扎实的开发者才应该使用它。如果能把这句警示时刻放在心里,那么反射机制就会成为一项强大的技术,可以让应用程序做一些几乎不可能做到的事情。


反射的缺点 Drawbacks of Reflection
Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.
尽管反射非常强大,但也不能滥用。如果一个功能可以不用反射完成,那么最好就不用。在我们使用反射技术时,下面几条内容应该牢记于心:

性能第一 Performance Overhead
Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
反射包括了一些动态类型,所以JVM无法对这些代码进行优化。因此,反射操作的效率要比那些非反射操作低得多。我们应该避免在经常被 执行的代码或对性能要求很高的程序中使用反射。
安全限制 Security Restrictions
Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.
使用反射技术要求程序必须在一个没有安全限制的环境中运行。如果一个程序必须在有安全限制的环境中运行,如Applet,那么这就是个问题了。。
内部暴露 Exposure of Internals
Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.
由于反射允许代码执行一些在正常情况下不被允许的操作(比如访问私有的属性和方法),所以使用反射可能会导致意料之外的副作用--代码有功能上的错误,降低可移植性。反射代码破坏了抽象性,因此当平台发生改变的时候,代码的行为就有可能也随着变化。

5.方法五(文章主题)
熟读设计模式七大原则的我怎么也得写一个自己满意的,直接上代码

public interface IStatus {
    public int getIndex();
    public String getName();
}
public class BaseType< T extends IStatus > {
	//通用核心
   	public  Map<String,Object> getStatusList(T[] t){
        Map<String,Object> map = new HashMap<String,Object>();
        Map<Integer,Object> json = new HashMap<Integer, Object>();
        for (T as: t) {
            json.put(as.getIndex(),as.getName());
        }
        map.put("data", json);
        map.put("state","ok");
        return map;
    }
}
public enum FundIoStatus implements IStatus{
    satatus1(1,"处理中"),
    satatus2(2,"处理成功"),
    satatus3(3,"处理失败"),
    satatus7(7,"超时未支付"),
    ;
    private int index;
    private String name;
    FundIoStatus(int index, String name){
        this.index = index;
        this.name = name;
    }
    @Override
    public int getIndex() {
        return index;
    }
    @Override
    public String getName() {
        return name;
    }
}
@Controller
public class PaymentController {
    @RequestMapping("/getFundIoStatus_sq")
    @ResponseBody
    public Object getFundIoStatus(){
        return new BaseStatus().getStatusList(FundIoStatus.values());
    }
}

自我自夸一下
优点
1.遍历对象很灵活,只要新增的枚举类假如类名为NewEnum按照以上枚举类格式书写,并实现IStatus接口,那么都可以通过new BaseStatus().getStatusList(NewEnum.values())来获得遍历的结果。(就是复用了枚举的遍历,同事B方法的优化版)
2.避免使用反射机制


版权声明:本文为weixin_42939779原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。