1.整合Jackson
根据《阿里巴巴开发规范》,包名使用单数,类名可以使用复数。
所以generic-common创建util包和utils工具类
很多时候我们需要将接收到的json数据转换为对象,或者将对象转为json存储。这时候我们需要编写用于json转换的工具类。
新建util目录,再创建JacksonUtils类
/*** JSON格式转换的工具类*/
public class JacksonUtils {private JacksonUtils() {}public final static ObjectMapper MAPPER;static {MAPPER = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);}public static String serialize(Object obj) {try {return MAPPER.writeValueAsString(obj);} catch (JsonProcessingException e) {e.printStackTrace();}return null;}public static Object deserialize(String jsonText, TypeReference type) {try {return MAPPER.readValue(jsonText, type);} catch (Exception e) {e.printStackTrace();}return null;}public static <T> T deserialize(String jsonText, Class<T> beanClass) {try {return MAPPER.readValue(jsonText, beanClass);} catch (Exception e) {e.printStackTrace();}return null;}public static JsonNode deserialize(String jsonText) {try {return MAPPER.readTree(jsonText);} catch (Exception e) {e.printStackTrace();}return null;}
}
2.反射工具类ReflectionUtils
/*** 反射相关方法*/
public class ReflectionUtils {/*** 根据方法名调用指定对象的方法* @param object 要调用方法的对象* @param method 要调用的方法名* @param args 参数对象数组* @return*/public static Object invoke(Object object, String method, Object... args) {Object result = null;Class<? extends Object> clazz = object.getClass();Method queryMethod = getMethod(clazz, method, args);if(queryMethod != null) {try {result = queryMethod.invoke(object, args);} catch (IllegalAccessException e) {e.printStackTrace();} catch (IllegalArgumentException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}} else {try {throw new NoSuchMethodException(clazz.getName() + " 类中没有找到 " + method + " 方法。");} catch (NoSuchMethodException e) {e.printStackTrace();}}return result;}/*** 根据方法名和参数对象查找方法* @param clazz* @param name* @param args 参数实例数据* @return*/public static Method getMethod(Class<? extends Object> clazz, String name, Object[] args) {Method queryMethod = null;Method[] methods = clazz.getMethods();for(Method method:methods) {if(method.getName().equals(name)) {Class<?>[] parameterTypes = method.getParameterTypes();if(parameterTypes.length == args.length) {boolean isSameMethod = true;for(int i=0; i<parameterTypes.length; i++) {Object arg = args[i];if(arg == null) {arg = "";}if(!parameterTypes[i].equals(args[i].getClass())) {isSameMethod = false;}}if(isSameMethod) {queryMethod = method;break ;}}}}return queryMethod;}
}