开发利器Hutool之MapProxy的妙用

开发 前端
目前公司项目中主要采用Hutool作为项目的工具包,相对于google的guava, hutool的工具类采用中文注释,更加符合国人使用。所谓知己知彼,我们需要了解Hutool都具有什么样的功能,才能够最大化发挥它的价值。

概述

Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。

目前公司项目中主要采用Hutool作为项目的工具包,相对于google的guava, hutool的工具类采用中文注释,更加符合国人使用。所谓知己知彼,我们需要了解Hutool都具有什么样的功能,才能够最大化发挥它的价值。

本文主要就hutool 5.8.8版本中MapProxy的使用。

场景引入

其实Map在get的时候是比较危险的,你可能不知道它是什么类型,需要进行强制,举个例子如下:

@Test
public void testMapProxy1() {
Map<String, Object> userMap = MapUtil.newHashMap(16);
userMap.put("username", "alvin");
userMap.put("age", 20);

// 使用map的时候, 需要进行强转,一旦类型错误,会报错
String age = (String)userMap.get("age");
}

运行结果:

图片

那有什么更好的解决方案吗?Hutool提供了一种解决方案给我们。

MapProxy使用

依赖引入

<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.8</version>
</dependency>

定义一个可访问接口

interface MapUser {
String getUsername();

Integer getAge();

MapUser setAge(Integer age);
}

通过MapProxy访问

@Test
public void testMapProxy2() {
Map<String, Object> userMap = MapUtil.newHashMap(16);
userMap.put("username", "alvin");
userMap.put("age", 20);

MapProxy mapProxy = MapProxy.create(userMap);
Integer age = mapProxy.getInt("age", 18);
Assert.assertTrue(age == 20);

// 通过代理的方式
MapUser mapUser = mapProxy.toProxyBean(MapUser.class);
// 后续访问会变的更加安全
Assert.assertTrue(mapUser.getAge() == 20);

mapUser.setAge(30);
Assert.assertTrue(mapUser.getAge() == 30);
}

MapProxy源码解析

Map代理,提供各种getXXX方法,并提供默认值支持,它的类结构图如下:

图片

  • 实现了OptNullBasicTypeFromObjectGetter接口, 提供了基本类型的get, 在不提供默认值的情况下, 如果值不存在或获取错误,返回null, 比如:mapProxy.getInt("age", 18)
  • 实现了InvocationHandler接口,支持jdk的动态代理,生成代理对象。
public <T> T toProxyBean(Class<T> interfaceClass) {
return (T) Proxy.newProxyInstance(ClassLoaderUtil.getClassLoader(), new Class<?>[]{interfaceClass}, this);
}
  • toProxyBean方法就是生成代理对象,最终会调用代理类的invoke方法,这里的代理类就是MapProxy本身。
public Object invoke(Object proxy, Method method, Object[] args) {
final Class<?>[] parameterTypes = method.getParameterTypes();
// 如果调用方法参数为空
if (ArrayUtil.isEmpty(parameterTypes)) {
final Class<?> returnType = method.getReturnType();
// 方法返回值不是void
if (void.class != returnType) {
// 匹配Getter
final String methodName = method.getName();
String fieldName = null;
if (methodName.startsWith("get")) {
// 匹配getXXX
fieldName = StrUtil.removePreAndLowerFirst(methodName, 3);
} else if (BooleanUtil.isBoolean(returnType) && methodName.startsWith("is")) {
// 匹配isXXX
fieldName = StrUtil.removePreAndLowerFirst(methodName, 2);
}else if ("hashCode".equals(methodName)) {
return this.hashCode();
} else if ("toString".equals(methodName)) {
return this.toString();
}

if (StrUtil.isNotBlank(fieldName)) {
if (false == this.containsKey(fieldName)) {
// 驼峰不存在转下划线尝试
fieldName = StrUtil.toUnderlineCase(fieldName);
}
return Convert.convert(method.getGenericReturnType(), this.get(fieldName));
}
}

// 如果方法参数不为空
} else if (1 == parameterTypes.length) {
// 匹配Setter
final String methodName = method.getName();
if (methodName.startsWith("set")) {
final String fieldName = StrUtil.removePreAndLowerFirst(methodName, 3);
if (StrUtil.isNotBlank(fieldName)) {
this.put(fieldName, args[0]);
final Class<?> returnType = method.getReturnType();
// 判断返回类型是不是代理类的实例
if(returnType.isInstance(proxy)){
return proxy;
}
}
} else if ("equals".equals(methodName)) {
return this.equals(args[0]);
}
}

throw new UnsupportedOperationException(method.toGenericString());
}

总结

本文主要讲解了Hutool中的MapProxy类的使用,希望对大家有帮助。

责任编辑:武晓燕 来源: JAVA旭阳
相关推荐

2019-10-18 16:05:32

框架开发Java

2022-09-21 08:16:18

缓存框架

2024-03-19 07:00:00

C++编程pragma

2022-10-26 09:57:52

VectorRustC++

2018-11-26 07:04:59

神经网络优化函数

2023-10-16 16:05:44

PythonPyCharm编程语言

2021-09-02 07:04:44

Go 开发利器

2023-07-19 12:24:48

C++constexpr​语句

2023-09-28 21:39:26

HutoolJava工具包

2010-03-10 17:57:54

Python编程语言

2024-03-05 10:41:51

Rollup前端开发

2024-03-22 09:45:34

大型语言模型Unity引擎游戏开发

2012-06-25 17:21:15

天天记事

2011-11-14 09:17:14

Linux运维ClusterShel

2024-04-25 08:22:43

AndroidlargeHeap属性

2021-08-30 10:19:05

PyFlink 开发环境Zeppelin No

2021-12-09 06:59:24

FlinkSQL 开发

2013-07-19 09:47:57

White ElephHadoopLinkedIn

2010-08-03 13:27:04

FlexBuilder

2013-08-20 14:13:01

网站开发编程
点赞
收藏

51CTO技术栈公众号