From f10d080d456643bbcb07301e4080ec5291fa85cc Mon Sep 17 00:00:00 2001 From: luyanbo Date: Sun, 29 Aug 2021 12:50:58 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8Djdk9=E6=A8=A1=E5=9D=97?= =?UTF-8?q?=E5=8C=96=E5=AF=BC=E8=87=B4=E7=9A=84NoClassDefFoundError:=20jav?= =?UTF-8?q?a/sql/Timestamp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/alibaba/fastjson/JSONArray.java | 4 +- .../java/com/alibaba/fastjson/JSONObject.java | 4 +- .../alibaba/fastjson/parser/ParserConfig.java | 63 +- .../com/alibaba/fastjson/util/Function.java | 10 + .../com/alibaba/fastjson/util/ModuleUtil.java | 34 + .../com/alibaba/fastjson/util/TypeUtils.java | 1506 +++++++++-------- 6 files changed, 863 insertions(+), 758 deletions(-) create mode 100644 src/main/java/com/alibaba/fastjson/util/Function.java create mode 100644 src/main/java/com/alibaba/fastjson/util/ModuleUtil.java diff --git a/src/main/java/com/alibaba/fastjson/JSONArray.java b/src/main/java/com/alibaba/fastjson/JSONArray.java index 6c11905d2..8d39a8e5d 100644 --- a/src/main/java/com/alibaba/fastjson/JSONArray.java +++ b/src/main/java/com/alibaba/fastjson/JSONArray.java @@ -429,13 +429,13 @@ public class JSONArray extends JSON implements List, Cloneable, RandomAc return castToDate(value); } - public java.sql.Date getSqlDate(int index) { + public Object getSqlDate(int index) { Object value = get(index); return castToSqlDate(value); } - public java.sql.Timestamp getTimestamp(int index) { + public Object getTimestamp(int index) { Object value = get(index); return castToTimestamp(value); diff --git a/src/main/java/com/alibaba/fastjson/JSONObject.java b/src/main/java/com/alibaba/fastjson/JSONObject.java index 48c041402..d18b9f254 100644 --- a/src/main/java/com/alibaba/fastjson/JSONObject.java +++ b/src/main/java/com/alibaba/fastjson/JSONObject.java @@ -337,13 +337,13 @@ public class JSONObject extends JSON implements Map, Cloneable, return castToDate(value); } - public java.sql.Date getSqlDate(String key) { + public Object getSqlDate(String key) { Object value = get(key); return castToSqlDate(value); } - public java.sql.Timestamp getTimestamp(String key) { + public Object getTimestamp(String key) { Object value = get(key); return castToTimestamp(value); diff --git a/src/main/java/com/alibaba/fastjson/parser/ParserConfig.java b/src/main/java/com/alibaba/fastjson/parser/ParserConfig.java index 9da6e47a4..a5230c437 100644 --- a/src/main/java/com/alibaba/fastjson/parser/ParserConfig.java +++ b/src/main/java/com/alibaba/fastjson/parser/ParserConfig.java @@ -31,6 +31,7 @@ import java.nio.charset.Charset; import java.security.AccessControlException; import java.text.SimpleDateFormat; import java.util.*; +import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; @@ -401,12 +402,18 @@ public class ParserConfig { } + private final Callable initDeserializersWithJavaSql = new Callable() { + public Void call() { + deserializers.put(java.sql.Timestamp.class, SqlDateDeserializer.instance_timestamp); + deserializers.put(java.sql.Date.class, SqlDateDeserializer.instance); + deserializers.put(java.sql.Time.class, TimeDeserializer.instance); + deserializers.put(java.util.Date.class, DateCodec.instance); + return null; + } + }; + private void initDeserializers() { deserializers.put(SimpleDateFormat.class, MiscCodec.instance); - deserializers.put(java.sql.Timestamp.class, SqlDateDeserializer.instance_timestamp); - deserializers.put(java.sql.Date.class, SqlDateDeserializer.instance); - deserializers.put(java.sql.Time.class, TimeDeserializer.instance); - deserializers.put(java.util.Date.class, DateCodec.instance); deserializers.put(Calendar.class, CalendarCodec.instance); deserializers.put(XMLGregorianCalendar.class, CalendarCodec.instance); @@ -482,6 +489,7 @@ public class ParserConfig { deserializers.put(Closeable.class, JavaObjectDeserializer.instance); deserializers.put(JSONPObject.class, new JSONPDeserializer()); + ModuleUtil.callWhenHasJavaSql(initDeserializersWithJavaSql); } private static String[] splitItemsFormProperty(final String property ){ @@ -1155,28 +1163,37 @@ public class ParserConfig { return isPrimitive2(clazz); } + private static Function, Boolean> isPrimitiveFuncation = new Function, Boolean>() { + public Boolean apply(Class clazz) { + return clazz == java.sql.Date.class // + || clazz == java.sql.Time.class // + || clazz == java.sql.Timestamp.class; + } + }; + /** * @deprecated internal method, dont call */ - public static boolean isPrimitive2(Class clazz) { - return clazz.isPrimitive() // - || clazz == Boolean.class // - || clazz == Character.class // - || clazz == Byte.class // - || clazz == Short.class // - || clazz == Integer.class // - || clazz == Long.class // - || clazz == Float.class // - || clazz == Double.class // - || clazz == BigInteger.class // - || clazz == BigDecimal.class // - || clazz == String.class // - || clazz == java.util.Date.class // - || clazz == java.sql.Date.class // - || clazz == java.sql.Time.class // - || clazz == java.sql.Timestamp.class // - || clazz.isEnum() // - ; + public static boolean isPrimitive2(final Class clazz) { + Boolean primitive = clazz.isPrimitive() // + || clazz == Boolean.class // + || clazz == Character.class // + || clazz == Byte.class // + || clazz == Short.class // + || clazz == Integer.class // + || clazz == Long.class // + || clazz == Float.class // + || clazz == Double.class // + || clazz == BigInteger.class // + || clazz == BigDecimal.class // + || clazz == String.class // + || clazz == java.util.Date.class // + || clazz.isEnum() // + ; + if (!primitive) { + primitive = ModuleUtil.callWhenHasJavaSql(isPrimitiveFuncation, clazz); + } + return primitive != null ? primitive : false; } /** diff --git a/src/main/java/com/alibaba/fastjson/util/Function.java b/src/main/java/com/alibaba/fastjson/util/Function.java new file mode 100644 index 000000000..0d4353387 --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/util/Function.java @@ -0,0 +1,10 @@ +package com.alibaba.fastjson.util; + +public interface Function { + /** + * Computes a result + * + * @return computed result + */ + V apply(ARG arg); +} diff --git a/src/main/java/com/alibaba/fastjson/util/ModuleUtil.java b/src/main/java/com/alibaba/fastjson/util/ModuleUtil.java new file mode 100644 index 000000000..7bd780dba --- /dev/null +++ b/src/main/java/com/alibaba/fastjson/util/ModuleUtil.java @@ -0,0 +1,34 @@ +package com.alibaba.fastjson.util; + +import java.util.concurrent.Callable; + +public class ModuleUtil { + private static boolean hasJavaSql = false; + + static { + try { + Class.forName("java.sql.Time"); + hasJavaSql = true; + } catch (Throwable e) { + hasJavaSql = false; + } + } + + public static T callWhenHasJavaSql(Callable callable) { + if (hasJavaSql) { + try { + return callable.call(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + return null; + } + + public static T callWhenHasJavaSql(Function callable, ARG arg) { + if (hasJavaSql) { + return callable.apply(arg); + } + return null; + } +} diff --git a/src/main/java/com/alibaba/fastjson/util/TypeUtils.java b/src/main/java/com/alibaba/fastjson/util/TypeUtils.java index 2f2c9a8aa..0fb843a80 100644 --- a/src/main/java/com/alibaba/fastjson/util/TypeUtils.java +++ b/src/main/java/com/alibaba/fastjson/util/TypeUtils.java @@ -39,9 +39,11 @@ import java.lang.reflect.*; import java.math.BigDecimal; import java.math.BigInteger; import java.security.AccessControlException; +import java.sql.Clob; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; +import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.regex.Matcher; @@ -50,11 +52,13 @@ import java.util.regex.Pattern; /** * @author wenshao[szujobs@hotmail.com] */ -public class TypeUtils{ +public class TypeUtils { private static final Pattern NUMBER_WITH_TRAILING_ZEROS_PATTERN = Pattern.compile("\\.0*$"); public static boolean compatibleWithJavaBean = false; - /** 根据field name的大小写输出输入数据 */ + /** + * 根据field name的大小写输出输入数据 + */ public static boolean compatibleWithFieldName = false; private static boolean setAccessibleEnable = true; private static boolean oracleTimestampMethodInited = false; @@ -81,18 +85,15 @@ public class TypeUtils{ private static volatile Method kotlin_kfunction_getParameters; private static volatile Method kotlin_kparameter_getName; private static volatile boolean kotlin_error; - private static volatile Map kotlinIgnores; + private static volatile Map kotlinIgnores; private static volatile boolean kotlinIgnores_error; - private static ConcurrentMap> mappings = new ConcurrentHashMap>(256, 0.75f, 1); + private static ConcurrentMap> mappings = new ConcurrentHashMap>(256, 0.75f, 1); private static Class pathClass; private static boolean pathClass_error = false; private static Class class_JacksonCreator = null; private static boolean class_JacksonCreator_error = false; - private static volatile Class class_Clob = null; - private static volatile boolean class_Clob_error = false; - private static volatile Class class_XmlAccessType = null; private static volatile Class class_XmlAccessorType = null; private static volatile boolean classXmlAccessorType_error = false; @@ -117,7 +118,7 @@ public class TypeUtils{ } } - static{ + static { addBaseClassMappings(); } @@ -126,7 +127,7 @@ public class TypeUtils{ if (class_XmlAccessorType == null && !classXmlAccessorType_error) { try { class_XmlAccessorType = Class.forName("javax.xml.bind.annotation.XmlAccessorType"); - } catch(Throwable ex){ + } catch (Throwable ex) { classXmlAccessorType_error = true; } } @@ -143,7 +144,7 @@ public class TypeUtils{ if (method_XmlAccessorType_value == null && !classXmlAccessorType_error) { try { method_XmlAccessorType_value = class_XmlAccessorType.getMethod("value"); - } catch(Throwable ex){ + } catch (Throwable ex) { classXmlAccessorType_error = true; } } @@ -169,7 +170,7 @@ public class TypeUtils{ class_XmlAccessType = Class.forName("javax.xml.bind.annotation.XmlAccessType"); field_XmlAccessType_FIELD = class_XmlAccessType.getField("FIELD"); field_XmlAccessType_FIELD_VALUE = field_XmlAccessType_FIELD.get(null); - } catch(Throwable ex){ + } catch (Throwable ex) { classXmlAccessorType_error = true; } } @@ -180,9 +181,9 @@ public class TypeUtils{ public static Annotation getXmlAccessorType(Class clazz) { if (class_XmlAccessorType == null && !classXmlAccessorType_error) { - try{ + try { class_XmlAccessorType = Class.forName("javax.xml.bind.annotation.XmlAccessorType"); - } catch(Throwable ex){ + } catch (Throwable ex) { classXmlAccessorType_error = true; } } @@ -191,7 +192,7 @@ public class TypeUtils{ return null; } - return TypeUtils.getAnnotation(clazz, class_XmlAccessorType); + return TypeUtils.getAnnotation(clazz, class_XmlAccessorType); } // @@ -212,48 +213,43 @@ public class TypeUtils{ // return class_XmlAccessType.isAssignableFrom(clazz); // } - public static boolean isClob(Class clazz) { - if (class_Clob == null && !class_Clob_error) { - - try{ - class_Clob = Class.forName("java.sql.Clob"); - } catch(Throwable ex){ - class_Clob_error = true; - } + private static Function isClobFunction = new Function() { + public Boolean apply(Class clazz) { + return Clob.class.isAssignableFrom(clazz); } + }; - if (class_Clob == null) { - return false; - } + public static boolean isClob(final Class clazz) { + Boolean isClob = ModuleUtil.callWhenHasJavaSql(isClobFunction, clazz); - return class_Clob.isAssignableFrom(clazz); + return isClob != null ? isClob : false; } - public static String castToString(Object value){ - if(value == null){ + public static String castToString(Object value) { + if (value == null) { return null; } return value.toString(); } - public static Byte castToByte(Object value){ - if(value == null){ + public static Byte castToByte(Object value) { + if (value == null) { return null; } - if(value instanceof BigDecimal){ + if (value instanceof BigDecimal) { return byteValue((BigDecimal) value); } - if(value instanceof Number){ + if (value instanceof Number) { return ((Number) value).byteValue(); } - if(value instanceof String){ + if (value instanceof String) { String strVal = (String) value; - if(strVal.length() == 0 // + if (strVal.length() == 0 // || "null".equals(strVal) // - || "NULL".equals(strVal)){ + || "NULL".equals(strVal)) { return null; } return Byte.parseByte(strVal); @@ -266,19 +262,19 @@ public class TypeUtils{ throw new JSONException("can not cast to byte, value : " + value); } - public static Character castToChar(Object value){ - if(value == null){ + public static Character castToChar(Object value) { + if (value == null) { return null; } - if(value instanceof Character){ + if (value instanceof Character) { return (Character) value; } - if(value instanceof String){ + if (value instanceof String) { String strVal = (String) value; - if(strVal.length() == 0){ + if (strVal.length() == 0) { return null; } - if(strVal.length() != 1){ + if (strVal.length() != 1) { throw new JSONException("can not cast to char, value : " + value); } return strVal.charAt(0); @@ -286,24 +282,24 @@ public class TypeUtils{ throw new JSONException("can not cast to char, value : " + value); } - public static Short castToShort(Object value){ - if(value == null){ + public static Short castToShort(Object value) { + if (value == null) { return null; } - if(value instanceof BigDecimal){ + if (value instanceof BigDecimal) { return shortValue((BigDecimal) value); } - if(value instanceof Number){ + if (value instanceof Number) { return ((Number) value).shortValue(); } - if(value instanceof String){ + if (value instanceof String) { String strVal = (String) value; - if(strVal.length() == 0 // + if (strVal.length() == 0 // || "null".equals(strVal) // - || "NULL".equals(strVal)){ + || "NULL".equals(strVal)) { return null; } return Short.parseShort(strVal); @@ -316,7 +312,7 @@ public class TypeUtils{ throw new JSONException("can not cast to short, value : " + value); } - public static BigDecimal castToBigDecimal(Object value){ + public static BigDecimal castToBigDecimal(Object value) { if (value == null) { return null; } @@ -390,21 +386,21 @@ public class TypeUtils{ return new BigInteger(strVal); } - public static Float castToFloat(Object value){ - if(value == null){ + public static Float castToFloat(Object value) { + if (value == null) { return null; } - if(value instanceof Number){ + if (value instanceof Number) { return ((Number) value).floatValue(); } - if(value instanceof String){ + if (value instanceof String) { String strVal = value.toString(); - if(strVal.length() == 0 // + if (strVal.length() == 0 // || "null".equals(strVal) // - || "NULL".equals(strVal)){ + || "NULL".equals(strVal)) { return null; } - if(strVal.indexOf(',') != -1){ + if (strVal.indexOf(',') != -1) { strVal = strVal.replaceAll(",", ""); } return Float.parseFloat(strVal); @@ -417,21 +413,21 @@ public class TypeUtils{ throw new JSONException("can not cast to float, value : " + value); } - public static Double castToDouble(Object value){ - if(value == null){ + public static Double castToDouble(Object value) { + if (value == null) { return null; } - if(value instanceof Number){ + if (value instanceof Number) { return ((Number) value).doubleValue(); } - if(value instanceof String){ + if (value instanceof String) { String strVal = value.toString(); - if(strVal.length() == 0 // + if (strVal.length() == 0 // || "null".equals(strVal) // - || "NULL".equals(strVal)){ + || "NULL".equals(strVal)) { return null; } - if(strVal.indexOf(',') != -1){ + if (strVal.indexOf(',') != -1) { strVal = strVal.replaceAll(",", ""); } return Double.parseDouble(strVal); @@ -444,31 +440,31 @@ public class TypeUtils{ throw new JSONException("can not cast to double, value : " + value); } - public static Date castToDate(Object value){ + public static Date castToDate(Object value) { return castToDate(value, null); } - public static Date castToDate(Object value, String format){ - if(value == null){ + public static Date castToDate(Object value, String format) { + if (value == null) { return null; } - if(value instanceof Date){ // 使用频率最高的,应优先处理 + if (value instanceof Date) { // 使用频率最高的,应优先处理 return (Date) value; } - if(value instanceof Calendar){ + if (value instanceof Calendar) { return ((Calendar) value).getTime(); } long longValue = -1; - if(value instanceof BigDecimal){ + if (value instanceof BigDecimal) { longValue = longValue((BigDecimal) value); return new Date(longValue); } - if(value instanceof Number){ + if (value instanceof Number) { longValue = ((Number) value).longValue(); if ("unixtime".equals(format)) { longValue *= 1000; @@ -476,15 +472,15 @@ public class TypeUtils{ return new Date(longValue); } - if(value instanceof String){ + if (value instanceof String) { String strVal = (String) value; JSONScanner dateLexer = new JSONScanner(strVal); - try{ - if(dateLexer.scanISO8601DateIfMatch(false)){ + try { + if (dateLexer.scanISO8601DateIfMatch(false)) { Calendar calendar = dateLexer.getCalendar(); return calendar.getTime(); } - } finally{ + } finally { dateLexer.close(); } @@ -515,13 +511,13 @@ public class TypeUtils{ SimpleDateFormat dateFormat = new SimpleDateFormat(format, JSON.defaultLocale); dateFormat.setTimeZone(JSON.defaultTimeZone); - try{ + try { return dateFormat.parse(strVal); - } catch(ParseException e){ + } catch (ParseException e) { throw new JSONException("can not cast to Date, value : " + strVal); } } - if(strVal.length() == 0){ + if (strVal.length() == 0) { return null; } longValue = Long.parseLong(strVal); @@ -529,38 +525,38 @@ public class TypeUtils{ if (longValue == -1) { Class clazz = value.getClass(); - if("oracle.sql.TIMESTAMP".equals(clazz.getName())){ - if(oracleTimestampMethod == null && !oracleTimestampMethodInited){ - try{ + if ("oracle.sql.TIMESTAMP".equals(clazz.getName())) { + if (oracleTimestampMethod == null && !oracleTimestampMethodInited) { + try { oracleTimestampMethod = clazz.getMethod("toJdbc"); - } catch(NoSuchMethodException e){ + } catch (NoSuchMethodException e) { // skip - } finally{ + } finally { oracleTimestampMethodInited = true; } } Object result; - try{ + try { result = oracleTimestampMethod.invoke(value); - } catch(Exception e){ + } catch (Exception e) { throw new JSONException("can not cast oracle.sql.TIMESTAMP to Date", e); } return (Date) result; } - if("oracle.sql.DATE".equals(clazz.getName())){ - if(oracleDateMethod == null && !oracleDateMethodInited){ - try{ + if ("oracle.sql.DATE".equals(clazz.getName())) { + if (oracleDateMethod == null && !oracleDateMethodInited) { + try { oracleDateMethod = clazz.getMethod("toJdbc"); - } catch(NoSuchMethodException e){ + } catch (NoSuchMethodException e) { // skip - } finally{ + } finally { oracleDateMethodInited = true; } } Object result; - try{ + try { result = oracleDateMethod.invoke(value); - } catch(Exception e){ + } catch (Exception e) { throw new JSONException("can not cast oracle.sql.DATE to Date", e); } return (Date) result; @@ -572,49 +568,55 @@ public class TypeUtils{ return new Date(longValue); } - public static java.sql.Date castToSqlDate(Object value){ - if(value == null){ - return null; - } - if(value instanceof java.sql.Date){ - return (java.sql.Date) value; - } - if(value instanceof java.util.Date){ - return new java.sql.Date(((java.util.Date) value).getTime()); - } - if(value instanceof Calendar){ - return new java.sql.Date(((Calendar) value).getTimeInMillis()); - } - - long longValue = 0; - if(value instanceof BigDecimal){ - longValue = longValue((BigDecimal) value); - } else if(value instanceof Number){ - longValue = ((Number) value).longValue(); - } - - if(value instanceof String){ - String strVal = (String) value; - if(strVal.length() == 0 // - || "null".equals(strVal) // - || "NULL".equals(strVal)){ + private static Function castToSqlDateFunction = new Function() { + public Object apply(Object value) { + if (value == null) { return null; } - if(isNumber(strVal)){ - longValue = Long.parseLong(strVal); - } else{ - JSONScanner scanner = new JSONScanner(strVal); - if(scanner.scanISO8601DateIfMatch(false)){ - longValue = scanner.getCalendar().getTime().getTime(); - } else{ - throw new JSONException("can not cast to Timestamp, value : " + strVal); + if (value instanceof java.sql.Date) { + return (java.sql.Date) value; + } + if (value instanceof Date) { + return new java.sql.Date(((Date) value).getTime()); + } + if (value instanceof Calendar) { + return new java.sql.Date(((Calendar) value).getTimeInMillis()); + } + + long longValue = 0; + if (value instanceof BigDecimal) { + longValue = longValue((BigDecimal) value); + } else if (value instanceof Number) { + longValue = ((Number) value).longValue(); + } + + if (value instanceof String) { + String strVal = (String) value; + if (strVal.length() == 0 // + || "null".equals(strVal) // + || "NULL".equals(strVal)) { + return null; + } + if (isNumber(strVal)) { + longValue = Long.parseLong(strVal); + } else { + JSONScanner scanner = new JSONScanner(strVal); + if (scanner.scanISO8601DateIfMatch(false)) { + longValue = scanner.getCalendar().getTime().getTime(); + } else { + throw new JSONException("can not cast to Timestamp, value : " + strVal); + } } } + if (longValue <= 0) { + throw new JSONException("can not cast to Date, value : " + value); // TODO 忽略 1970-01-01 之前的时间处理? + } + return new java.sql.Date(longValue); } - if(longValue <= 0){ - throw new JSONException("can not cast to Date, value : " + value); // TODO 忽略 1970-01-01 之前的时间处理? - } - return new java.sql.Date(longValue); + }; + + public static Object castToSqlDate(final Object value) { + return ModuleUtil.callWhenHasJavaSql(castToSqlDateFunction, value); } public static long longExtractValue(Number number) { @@ -625,142 +627,153 @@ public class TypeUtils{ return number.longValue(); } - public static java.sql.Time castToSqlTime(Object value){ - if(value == null){ - return null; - } - if(value instanceof java.sql.Time){ - return (java.sql.Time) value; - } - if(value instanceof java.util.Date){ - return new java.sql.Time(((java.util.Date) value).getTime()); - } - if(value instanceof Calendar){ - return new java.sql.Time(((Calendar) value).getTimeInMillis()); - } - - long longValue = 0; - if(value instanceof BigDecimal){ - longValue = longValue((BigDecimal) value); - } else if(value instanceof Number){ - longValue = ((Number) value).longValue(); - } - - if (value instanceof String) { - String strVal = (String) value; - if (strVal.length() == 0 // - || "null".equalsIgnoreCase(strVal)) { + private static Function castToSqlTimeFunction = new Function() { + public Object apply(Object value) { + if (value == null) { return null; } - - if (isNumber(strVal)) { - longValue = Long.parseLong(strVal); - } else { - if (strVal.length() == 8 && strVal.charAt(2) == ':' && strVal.charAt(5) == ':') { - return java.sql.Time.valueOf(strVal); - } - - JSONScanner scanner = new JSONScanner(strVal); - if (scanner.scanISO8601DateIfMatch(false)) { - longValue = scanner.getCalendar().getTime().getTime(); - } else { - throw new JSONException("can not cast to Timestamp, value : " + strVal); - } - + if (value instanceof java.sql.Time) { + return (java.sql.Time) value; } + if (value instanceof java.util.Date) { + return new java.sql.Time(((java.util.Date) value).getTime()); + } + if (value instanceof Calendar) { + return new java.sql.Time(((Calendar) value).getTimeInMillis()); + } + + long longValue = 0; + if (value instanceof BigDecimal) { + longValue = longValue((BigDecimal) value); + } else if (value instanceof Number) { + longValue = ((Number) value).longValue(); + } + + if (value instanceof String) { + String strVal = (String) value; + if (strVal.length() == 0 // + || "null".equalsIgnoreCase(strVal)) { + return null; + } + + if (isNumber(strVal)) { + longValue = Long.parseLong(strVal); + } else { + if (strVal.length() == 8 && strVal.charAt(2) == ':' && strVal.charAt(5) == ':') { + return java.sql.Time.valueOf(strVal); + } + + JSONScanner scanner = new JSONScanner(strVal); + if (scanner.scanISO8601DateIfMatch(false)) { + longValue = scanner.getCalendar().getTime().getTime(); + } else { + throw new JSONException("can not cast to Timestamp, value : " + strVal); + } + + } + } + if (longValue <= 0) { + throw new JSONException("can not cast to Date, value : " + value); // TODO 忽略 1970-01-01 之前的时间处理? + } + return new java.sql.Time(longValue); } - if(longValue <= 0){ - throw new JSONException("can not cast to Date, value : " + value); // TODO 忽略 1970-01-01 之前的时间处理? - } - return new java.sql.Time(longValue); + }; + + public static Object castToSqlTime(final Object value) { + return ModuleUtil.callWhenHasJavaSql(castToSqlTimeFunction, value); } - public static java.sql.Timestamp castToTimestamp(Object value){ - if(value == null){ - return null; - } - if(value instanceof Calendar){ - return new java.sql.Timestamp(((Calendar) value).getTimeInMillis()); - } - if(value instanceof java.sql.Timestamp){ - return (java.sql.Timestamp) value; - } - if(value instanceof java.util.Date){ - return new java.sql.Timestamp(((java.util.Date) value).getTime()); - } - long longValue = 0; - if(value instanceof BigDecimal){ - longValue = longValue((BigDecimal) value); - } else if(value instanceof Number){ - longValue = ((Number) value).longValue(); - } - if(value instanceof String){ - String strVal = (String) value; - if(strVal.length() == 0 // - || "null".equals(strVal) // - || "NULL".equals(strVal)){ + public static Function castToTimestampFunction = new Function() { + public Object apply(Object value) { + if (value == null) { return null; } - if(strVal.endsWith(".000000000")){ - strVal = strVal.substring(0, strVal.length() - 10); - } else if(strVal.endsWith(".000000")){ - strVal = strVal.substring(0, strVal.length() - 7); + if (value instanceof Calendar) { + return new java.sql.Timestamp(((Calendar) value).getTimeInMillis()); } - - if (strVal.length() == 29 - && strVal.charAt(4) == '-' - && strVal.charAt(7) == '-' - && strVal.charAt(10) == ' ' - && strVal.charAt(13) == ':' - && strVal.charAt(16) == ':' - && strVal.charAt(19) == '.') { - int year = num( - strVal.charAt(0), - strVal.charAt(1), - strVal.charAt(2), - strVal.charAt(3)); - int month = num( - strVal.charAt(5), - strVal.charAt(6)); - int day = num( - strVal.charAt(8), - strVal.charAt(9)); - int hour = num( - strVal.charAt(11), - strVal.charAt(12)); - int minute = num( - strVal.charAt(14), - strVal.charAt(15)); - int second = num( - strVal.charAt(17), - strVal.charAt(18)); - int nanos = num( - strVal.charAt(20), - strVal.charAt(21), - strVal.charAt(22), - strVal.charAt(23), - strVal.charAt(24), - strVal.charAt(25), - strVal.charAt(26), - strVal.charAt(27), - strVal.charAt(28)); - return new java.sql.Timestamp(year - 1900, month - 1, day, hour, minute, second, nanos); + if (value instanceof java.sql.Timestamp) { + return (java.sql.Timestamp) value; } + if (value instanceof java.util.Date) { + return new java.sql.Timestamp(((java.util.Date) value).getTime()); + } + long longValue = 0; + if (value instanceof BigDecimal) { + longValue = longValue((BigDecimal) value); + } else if (value instanceof Number) { + longValue = ((Number) value).longValue(); + } + if (value instanceof String) { + String strVal = (String) value; + if (strVal.length() == 0 // + || "null".equals(strVal) // + || "NULL".equals(strVal)) { + return null; + } + if (strVal.endsWith(".000000000")) { + strVal = strVal.substring(0, strVal.length() - 10); + } else if (strVal.endsWith(".000000")) { + strVal = strVal.substring(0, strVal.length() - 7); + } - if(isNumber(strVal)){ - longValue = Long.parseLong(strVal); - } else { - JSONScanner scanner = new JSONScanner(strVal); - if(scanner.scanISO8601DateIfMatch(false)){ - longValue = scanner.getCalendar().getTime().getTime(); - } else{ - throw new JSONException("can not cast to Timestamp, value : " + strVal); + if (strVal.length() == 29 + && strVal.charAt(4) == '-' + && strVal.charAt(7) == '-' + && strVal.charAt(10) == ' ' + && strVal.charAt(13) == ':' + && strVal.charAt(16) == ':' + && strVal.charAt(19) == '.') { + int year = num( + strVal.charAt(0), + strVal.charAt(1), + strVal.charAt(2), + strVal.charAt(3)); + int month = num( + strVal.charAt(5), + strVal.charAt(6)); + int day = num( + strVal.charAt(8), + strVal.charAt(9)); + int hour = num( + strVal.charAt(11), + strVal.charAt(12)); + int minute = num( + strVal.charAt(14), + strVal.charAt(15)); + int second = num( + strVal.charAt(17), + strVal.charAt(18)); + int nanos = num( + strVal.charAt(20), + strVal.charAt(21), + strVal.charAt(22), + strVal.charAt(23), + strVal.charAt(24), + strVal.charAt(25), + strVal.charAt(26), + strVal.charAt(27), + strVal.charAt(28)); + return new java.sql.Timestamp(year - 1900, month - 1, day, hour, minute, second, nanos); + } + + if (isNumber(strVal)) { + longValue = Long.parseLong(strVal); + } else { + JSONScanner scanner = new JSONScanner(strVal); + if (scanner.scanISO8601DateIfMatch(false)) { + longValue = scanner.getCalendar().getTime().getTime(); + } else { + throw new JSONException("can not cast to Timestamp, value : " + strVal); + } } } + + return new java.sql.Timestamp(longValue); } + }; - - return new java.sql.Timestamp(longValue); + public static Object castToTimestamp(final Object value) { + return ModuleUtil.callWhenHasJavaSql(castToTimestampFunction, value); } static int num(char c0, char c1) { @@ -829,64 +842,64 @@ public class TypeUtils{ return -1; } - public static boolean isNumber(String str){ - for(int i = 0; i < str.length(); ++i){ + public static boolean isNumber(String str) { + for (int i = 0; i < str.length(); ++i) { char ch = str.charAt(i); - if(ch == '+' || ch == '-'){ - if(i != 0){ + if (ch == '+' || ch == '-') { + if (i != 0) { return false; } - } else if(ch < '0' || ch > '9'){ + } else if (ch < '0' || ch > '9') { return false; } } return true; } - public static Long castToLong(Object value){ - if(value == null){ + public static Long castToLong(Object value) { + if (value == null) { return null; } - if(value instanceof BigDecimal){ + if (value instanceof BigDecimal) { return longValue((BigDecimal) value); } - if(value instanceof Number){ + if (value instanceof Number) { return ((Number) value).longValue(); } - if(value instanceof String){ + if (value instanceof String) { String strVal = (String) value; - if(strVal.length() == 0 // + if (strVal.length() == 0 // || "null".equals(strVal) // - || "NULL".equals(strVal)){ + || "NULL".equals(strVal)) { return null; } - if(strVal.indexOf(',') != -1){ + if (strVal.indexOf(',') != -1) { strVal = strVal.replaceAll(",", ""); } - try{ + try { return Long.parseLong(strVal); - } catch(NumberFormatException ex){ + } catch (NumberFormatException ex) { // } JSONScanner dateParser = new JSONScanner(strVal); Calendar calendar = null; - if(dateParser.scanISO8601DateIfMatch(false)){ + if (dateParser.scanISO8601DateIfMatch(false)) { calendar = dateParser.getCalendar(); } dateParser.close(); - if(calendar != null){ + if (calendar != null) { return calendar.getTimeInMillis(); } } - if(value instanceof Map){ + if (value instanceof Map) { Map map = (Map) value; - if(map.size() == 2 + if (map.size() == 2 && map.containsKey("andIncrement") - && map.containsKey("andDecrement")){ + && map.containsKey("andDecrement")) { Iterator iter = map.values().iterator(); iter.next(); Object value2 = iter.next(); @@ -953,49 +966,49 @@ public class TypeUtils{ return decimal.longValueExact(); } - public static Integer castToInt(Object value){ - if(value == null){ + public static Integer castToInt(Object value) { + if (value == null) { return null; } - if(value instanceof Integer){ + if (value instanceof Integer) { return (Integer) value; } - if(value instanceof BigDecimal){ + if (value instanceof BigDecimal) { return intValue((BigDecimal) value); } - if(value instanceof Number){ + if (value instanceof Number) { return ((Number) value).intValue(); } - if(value instanceof String){ + if (value instanceof String) { String strVal = (String) value; - if(strVal.length() == 0 // + if (strVal.length() == 0 // || "null".equals(strVal) // - || "NULL".equals(strVal)){ + || "NULL".equals(strVal)) { return null; } - if(strVal.indexOf(',') != -1){ + if (strVal.indexOf(',') != -1) { strVal = strVal.replaceAll(",", ""); } Matcher matcher = NUMBER_WITH_TRAILING_ZEROS_PATTERN.matcher(strVal); - if(matcher.find()) { + if (matcher.find()) { strVal = matcher.replaceAll(""); } return Integer.parseInt(strVal); } - if(value instanceof Boolean){ + if (value instanceof Boolean) { return (Boolean) value ? 1 : 0; } - if(value instanceof Map){ + if (value instanceof Map) { Map map = (Map) value; - if(map.size() == 2 + if (map.size() == 2 && map.containsKey("andIncrement") - && map.containsKey("andDecrement")){ + && map.containsKey("andDecrement")) { Iterator iter = map.values().iterator(); iter.next(); Object value2 = iter.next(); @@ -1005,198 +1018,207 @@ public class TypeUtils{ throw new JSONException("can not cast to int, value : " + value); } - public static byte[] castToBytes(Object value){ - if(value instanceof byte[]){ + public static byte[] castToBytes(Object value) { + if (value instanceof byte[]) { return (byte[]) value; } - if(value instanceof String){ + if (value instanceof String) { return IOUtils.decodeBase64((String) value); } throw new JSONException("can not cast to byte[], value : " + value); } - public static Boolean castToBoolean(Object value){ - if(value == null){ + public static Boolean castToBoolean(Object value) { + if (value == null) { return null; } - if(value instanceof Boolean){ + if (value instanceof Boolean) { return (Boolean) value; } - if(value instanceof BigDecimal){ + if (value instanceof BigDecimal) { return intValue((BigDecimal) value) == 1; } - if(value instanceof Number){ + if (value instanceof Number) { return ((Number) value).intValue() == 1; } - if(value instanceof String){ + if (value instanceof String) { String strVal = (String) value; - if(strVal.length() == 0 // + if (strVal.length() == 0 // || "null".equals(strVal) // - || "NULL".equals(strVal)){ + || "NULL".equals(strVal)) { return null; } - if("true".equalsIgnoreCase(strVal) // - || "1".equals(strVal)){ + if ("true".equalsIgnoreCase(strVal) // + || "1".equals(strVal)) { return Boolean.TRUE; } - if("false".equalsIgnoreCase(strVal) // - || "0".equals(strVal)){ + if ("false".equalsIgnoreCase(strVal) // + || "0".equals(strVal)) { return Boolean.FALSE; } - if("Y".equalsIgnoreCase(strVal) // - || "T".equals(strVal)){ + if ("Y".equalsIgnoreCase(strVal) // + || "T".equals(strVal)) { return Boolean.TRUE; } - if("F".equalsIgnoreCase(strVal) // - || "N".equals(strVal)){ + if ("F".equalsIgnoreCase(strVal) // + || "N".equals(strVal)) { return Boolean.FALSE; } } throw new JSONException("can not cast to boolean, value : " + value); } - public static T castToJavaBean(Object obj, Class clazz){ + public static T castToJavaBean(Object obj, Class clazz) { return cast(obj, clazz, ParserConfig.getGlobalInstance()); } @SuppressWarnings({"unchecked", "rawtypes"}) - public static T cast(Object obj, Class clazz, ParserConfig config){ - if(obj == null){ - if(clazz == int.class){ + public static T cast(final Object obj, final Class clazz, ParserConfig config) { + if (obj == null) { + if (clazz == int.class) { return (T) Integer.valueOf(0); - } else if(clazz == long.class){ + } else if (clazz == long.class) { return (T) Long.valueOf(0); - } else if(clazz == short.class){ + } else if (clazz == short.class) { return (T) Short.valueOf((short) 0); - } else if(clazz == byte.class){ + } else if (clazz == byte.class) { return (T) Byte.valueOf((byte) 0); - } else if(clazz == float.class){ + } else if (clazz == float.class) { return (T) Float.valueOf(0); - } else if(clazz == double.class){ + } else if (clazz == double.class) { return (T) Double.valueOf(0); - } else if(clazz == boolean.class){ + } else if (clazz == boolean.class) { return (T) Boolean.FALSE; } return null; } - if(clazz == null){ + if (clazz == null) { throw new IllegalArgumentException("clazz is null"); } - if(clazz == obj.getClass()){ + if (clazz == obj.getClass()) { return (T) obj; } - if(obj instanceof Map){ - if(clazz == Map.class){ + if (obj instanceof Map) { + if (clazz == Map.class) { return (T) obj; } Map map = (Map) obj; - if(clazz == Object.class && !map.containsKey(JSON.DEFAULT_TYPE_KEY)){ + if (clazz == Object.class && !map.containsKey(JSON.DEFAULT_TYPE_KEY)) { return (T) obj; } - return castToJavaBean((Map) obj, clazz, config); + return castToJavaBean((Map) obj, clazz, config); } - if(clazz.isArray()){ - if(obj instanceof Collection){ + if (clazz.isArray()) { + if (obj instanceof Collection) { Collection collection = (Collection) obj; int index = 0; Object array = Array.newInstance(clazz.getComponentType(), collection.size()); - for(Object item : collection){ + for (Object item : collection) { Object value = cast(item, clazz.getComponentType(), config); Array.set(array, index, value); index++; } return (T) array; } - if(clazz == byte[].class){ + if (clazz == byte[].class) { return (T) castToBytes(obj); } } - if(clazz.isAssignableFrom(obj.getClass())){ + if (clazz.isAssignableFrom(obj.getClass())) { return (T) obj; } - if(clazz == boolean.class || clazz == Boolean.class){ + if (clazz == boolean.class || clazz == Boolean.class) { return (T) castToBoolean(obj); } - if(clazz == byte.class || clazz == Byte.class){ + if (clazz == byte.class || clazz == Byte.class) { return (T) castToByte(obj); } - if(clazz == char.class || clazz == Character.class){ + if (clazz == char.class || clazz == Character.class) { return (T) castToChar(obj); } - if(clazz == short.class || clazz == Short.class){ + if (clazz == short.class || clazz == Short.class) { return (T) castToShort(obj); } - if(clazz == int.class || clazz == Integer.class){ + if (clazz == int.class || clazz == Integer.class) { return (T) castToInt(obj); } - if(clazz == long.class || clazz == Long.class){ + if (clazz == long.class || clazz == Long.class) { return (T) castToLong(obj); } - if(clazz == float.class || clazz == Float.class){ + if (clazz == float.class || clazz == Float.class) { return (T) castToFloat(obj); } - if(clazz == double.class || clazz == Double.class){ + if (clazz == double.class || clazz == Double.class) { return (T) castToDouble(obj); } - if(clazz == String.class){ + if (clazz == String.class) { return (T) castToString(obj); } - if(clazz == BigDecimal.class){ + if (clazz == BigDecimal.class) { return (T) castToBigDecimal(obj); } - if(clazz == BigInteger.class){ + if (clazz == BigInteger.class) { return (T) castToBigInteger(obj); } - if(clazz == Date.class){ + if (clazz == Date.class) { return (T) castToDate(obj); } - if(clazz == java.sql.Date.class){ - return (T) castToSqlDate(obj); + T retObj = (T) ModuleUtil.callWhenHasJavaSql(new Callable() { + public Object call() { + if (clazz == java.sql.Date.class) { + return (T) castToSqlDate(obj); + } + + if (clazz == java.sql.Time.class) { + return (T) castToSqlTime(obj); + } + + if (clazz == java.sql.Timestamp.class) { + return (T) castToTimestamp(obj); + } + return null; + } + }); + + if (retObj != null) { + return retObj; } - if(clazz == java.sql.Time.class){ - return (T) castToSqlTime(obj); - } - - if(clazz == java.sql.Timestamp.class){ - return (T) castToTimestamp(obj); - } - - if(clazz.isEnum()){ + if (clazz.isEnum()) { return castToEnum(obj, clazz, config); } - if(Calendar.class.isAssignableFrom(clazz)){ + if (Calendar.class.isAssignableFrom(clazz)) { Date date = castToDate(obj); Calendar calendar; - if(clazz == Calendar.class){ + if (clazz == Calendar.class) { calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); - } else{ - try{ + } else { + try { calendar = (Calendar) clazz.newInstance(); - } catch(Exception e){ + } catch (Exception e) { throw new JSONException("can not cast to : " + clazz.getName(), e); } } @@ -1205,26 +1227,26 @@ public class TypeUtils{ } String className = clazz.getName(); - if(className.equals("javax.xml.datatype.XMLGregorianCalendar")){ + if (className.equals("javax.xml.datatype.XMLGregorianCalendar")) { Date date = castToDate(obj); Calendar calendar = Calendar.getInstance(JSON.defaultTimeZone, JSON.defaultLocale); calendar.setTime(date); return (T) CalendarCodec.instance.createXMLGregorianCalendar(calendar); } - if(obj instanceof String){ + if (obj instanceof String) { String strVal = (String) obj; - if(strVal.length() == 0 // + if (strVal.length() == 0 // || "null".equals(strVal) // - || "NULL".equals(strVal)){ + || "NULL".equals(strVal)) { return null; } - if(clazz == java.util.Currency.class){ + if (clazz == java.util.Currency.class) { return (T) java.util.Currency.getInstance(strVal); } - if(clazz == java.util.Locale.class){ + if (clazz == java.util.Locale.class) { return (T) toLocale(strVal); } @@ -1242,23 +1264,23 @@ public class TypeUtils{ throw new JSONException("can not cast to : " + clazz.getName()); } - public static Locale toLocale(String strVal){ + public static Locale toLocale(String strVal) { String[] items = strVal.split("_"); - if(items.length == 1){ + if (items.length == 1) { return new Locale(items[0]); } - if(items.length == 2){ + if (items.length == 2) { return new Locale(items[0], items[1]); } return new Locale(items[0], items[1], items[2]); } @SuppressWarnings({"unchecked", "rawtypes"}) - public static T castToEnum(Object obj, Class clazz, ParserConfig mapping){ - try{ - if(obj instanceof String){ + public static T castToEnum(Object obj, Class clazz, ParserConfig mapping) { + try { + if (obj instanceof String) { String name = (String) obj; - if(name.length() == 0){ + if (name.length() == 0) { return null; } @@ -1275,47 +1297,47 @@ public class TypeUtils{ return (T) Enum.valueOf((Class) clazz, name); } - if(obj instanceof BigDecimal){ + if (obj instanceof BigDecimal) { int ordinal = intValue((BigDecimal) obj); Object[] values = clazz.getEnumConstants(); - if(ordinal < values.length){ + if (ordinal < values.length) { return (T) values[ordinal]; } } - if(obj instanceof Number){ + if (obj instanceof Number) { int ordinal = ((Number) obj).intValue(); Object[] values = clazz.getEnumConstants(); - if(ordinal < values.length){ + if (ordinal < values.length) { return (T) values[ordinal]; } } - } catch(Exception ex){ + } catch (Exception ex) { throw new JSONException("can not cast to : " + clazz.getName(), ex); } throw new JSONException("can not cast to : " + clazz.getName()); } @SuppressWarnings("unchecked") - public static T cast(Object obj, Type type, ParserConfig mapping){ - if(obj == null){ + public static T cast(Object obj, Type type, ParserConfig mapping) { + if (obj == null) { return null; } - if(type instanceof Class){ + if (type instanceof Class) { return cast(obj, (Class) type, mapping); } - if(type instanceof ParameterizedType){ + if (type instanceof ParameterizedType) { return (T) cast(obj, (ParameterizedType) type, mapping); } - if(obj instanceof String){ + if (obj instanceof String) { String strVal = (String) obj; - if(strVal.length() == 0 // + if (strVal.length() == 0 // || "null".equals(strVal) // - || "NULL".equals(strVal)){ + || "NULL".equals(strVal)) { return null; } } - if(type instanceof TypeVariable){ + if (type instanceof TypeVariable) { return (T) obj; } throw new JSONException("can not cast to : " + type); @@ -1325,9 +1347,9 @@ public class TypeUtils{ public static T cast(Object obj, ParameterizedType type, ParserConfig mapping) { Type rawTye = type.getRawType(); - if(rawTye == List.class || rawTye == ArrayList.class){ + if (rawTye == List.class || rawTye == ArrayList.class) { Type itemType = type.getActualTypeArguments()[0]; - if(obj instanceof List){ + if (obj instanceof List) { List listObj = (List) obj; List arrayList = new ArrayList(listObj.size()); @@ -1349,19 +1371,19 @@ public class TypeUtils{ } } - if(rawTye == Set.class || rawTye == HashSet.class // + if (rawTye == Set.class || rawTye == HashSet.class // || rawTye == TreeSet.class // || rawTye == Collection.class // || rawTye == List.class // - || rawTye == ArrayList.class){ + || rawTye == ArrayList.class) { Type itemType = type.getActualTypeArguments()[0]; - if(obj instanceof Iterable){ + if (obj instanceof Iterable) { Collection collection; - if(rawTye == Set.class || rawTye == HashSet.class){ + if (rawTye == Set.class || rawTye == HashSet.class) { collection = new HashSet(); - } else if(rawTye == TreeSet.class){ + } else if (rawTye == TreeSet.class) { collection = new TreeSet(); - } else{ + } else { collection = new ArrayList(); } for (Object item : (Iterable) obj) { @@ -1382,12 +1404,12 @@ public class TypeUtils{ } } - if(rawTye == Map.class || rawTye == HashMap.class){ + if (rawTye == Map.class || rawTye == HashMap.class) { Type keyType = type.getActualTypeArguments()[0]; Type valueType = type.getActualTypeArguments()[1]; - if(obj instanceof Map){ + if (obj instanceof Map) { Map map = new HashMap(); - for(Map.Entry entry : ((Map) obj).entrySet()){ + for (Map.Entry entry : ((Map) obj).entrySet()) { Object key = cast(entry.getKey(), keyType, mapping); Object value = cast(entry.getValue(), valueType, mapping); map.put(key, value); @@ -1395,9 +1417,9 @@ public class TypeUtils{ return (T) map; } } - if(obj instanceof String){ + if (obj instanceof String) { String strVal = (String) obj; - if(strVal.length() == 0){ + if (strVal.length() == 0) { return null; } } @@ -1405,7 +1427,7 @@ public class TypeUtils{ Type[] actualTypeArguments = type.getActualTypeArguments(); if (actualTypeArguments.length == 1) { Type argType = type.getActualTypeArguments()[0]; - if(argType instanceof WildcardType){ + if (argType instanceof WildcardType) { return (T) cast(obj, rawTye, mapping); } } @@ -1438,20 +1460,20 @@ public class TypeUtils{ } @SuppressWarnings({"unchecked"}) - public static T castToJavaBean(Map map, Class clazz, ParserConfig config){ - try{ - if(clazz == StackTraceElement.class){ + public static T castToJavaBean(Map map, Class clazz, ParserConfig config) { + try { + if (clazz == StackTraceElement.class) { String declaringClass = (String) map.get("className"); String methodName = (String) map.get("methodName"); String fileName = (String) map.get("fileName"); int lineNumber; { Number value = (Number) map.get("lineNumber"); - if(value == null) { + if (value == null) { lineNumber = 0; } else if (value instanceof BigDecimal) { lineNumber = ((BigDecimal) value).intValueExact(); - } else{ + } else { lineNumber = value.intValue(); } } @@ -1460,34 +1482,34 @@ public class TypeUtils{ { Object iClassObject = map.get(JSON.DEFAULT_TYPE_KEY); - if(iClassObject instanceof String){ + if (iClassObject instanceof String) { String className = (String) iClassObject; Class loadClazz; - if(config == null){ + if (config == null) { config = ParserConfig.global; } loadClazz = config.checkAutoType(className, null); - if(loadClazz == null){ + if (loadClazz == null) { throw new ClassNotFoundException(className + " not found"); } - if(!loadClazz.equals(clazz)){ + if (!loadClazz.equals(clazz)) { return (T) castToJavaBean(map, loadClazz, config); } } } - if(clazz.isInterface()){ + if (clazz.isInterface()) { JSONObject object; - if(map instanceof JSONObject){ + if (map instanceof JSONObject) { object = (JSONObject) map; - } else{ + } else { object = new JSONObject(map); } - if(config == null){ + if (config == null) { config = ParserConfig.getGlobalInstance(); } ObjectDeserializer deserializer = config.get(clazz); - if(deserializer != null){ + if (deserializer != null) { String json = JSON.toJSONString(object); return JSON.parseObject(json, clazz); } @@ -1495,15 +1517,15 @@ public class TypeUtils{ new Class[]{clazz}, object); } - if(clazz == Locale.class){ + if (clazz == Locale.class) { Object arg0 = map.get("language"); Object arg1 = map.get("country"); - if(arg0 instanceof String){ + if (arg0 instanceof String) { String language = (String) arg0; - if(arg1 instanceof String){ + if (arg1 instanceof String) { String country = (String) arg1; return (T) new Locale(language, country); - } else if(arg1 == null){ + } else if (arg1 == null) { return (T) new Locale(language); } } @@ -1543,16 +1565,33 @@ public class TypeUtils{ javaBeanDeser = (JavaBeanDeserializer) deserializer; } - if(javaBeanDeser == null){ + if (javaBeanDeser == null) { throw new JSONException("can not get javaBeanDeserializer. " + clazz.getName()); } return (T) javaBeanDeser.createInstance(map, config); - } catch(Exception e){ + } catch (Exception e) { throw new JSONException(e.getMessage(), e); } } - private static void addBaseClassMappings(){ + private static Callable addBaseClassMappingsFunction = new Callable() { + public Void call() { + Class[] classes = new Class[]{ + java.sql.Time.class, + java.sql.Date.class, + java.sql.Timestamp.class + }; + for (Class clazz : classes) { + if (clazz == null) { + continue; + } + mappings.put(clazz.getName(), clazz); + } + return null; + } + }; + + private static void addBaseClassMappings() { mappings.put("byte", byte.class); mappings.put("short", short.class); mappings.put("int", int.class); @@ -1643,23 +1682,21 @@ public class TypeUtils{ java.util.Date.class, java.util.Locale.class, java.util.UUID.class, - java.sql.Time.class, - java.sql.Date.class, - java.sql.Timestamp.class, java.text.SimpleDateFormat.class, com.alibaba.fastjson.JSONObject.class, com.alibaba.fastjson.JSONPObject.class, com.alibaba.fastjson.JSONArray.class, }; - for(Class clazz : classes){ - if(clazz == null){ + for (Class clazz : classes) { + if (clazz == null) { continue; } mappings.put(clazz.getName(), clazz); } + ModuleUtil.callWhenHasJavaSql(addBaseClassMappingsFunction); } - public static void clearClassMapping(){ + public static void clearClassMapping() { mappings.clear(); addBaseClassMappings(); } @@ -1668,25 +1705,25 @@ public class TypeUtils{ mappings.put(className, clazz); } - public static Class loadClass(String className){ + public static Class loadClass(String className) { return loadClass(className, null); } - public static boolean isPath(Class clazz){ - if(pathClass == null && !pathClass_error){ - try{ + public static boolean isPath(Class clazz) { + if (pathClass == null && !pathClass_error) { + try { pathClass = Class.forName("java.nio.file.Path"); - } catch(Throwable ex){ + } catch (Throwable ex) { pathClass_error = true; } } - if(pathClass != null){ + if (pathClass != null) { return pathClass.isAssignableFrom(clazz); } return false; } - public static Class getClassFromMapping(String className){ + public static Class getClassFromMapping(String className) { return mappings.get(className); } @@ -1695,7 +1732,7 @@ public class TypeUtils{ } public static Class loadClass(String className, ClassLoader classLoader, boolean cache) { - if(className == null || className.length() == 0){ + if (className == null || className.length() == 0) { return null; } @@ -1704,76 +1741,76 @@ public class TypeUtils{ } Class clazz = mappings.get(className); - if(clazz != null){ + if (clazz != null) { return clazz; } - if(className.charAt(0) == '['){ + if (className.charAt(0) == '[') { Class componentType = loadClass(className.substring(1), classLoader); return Array.newInstance(componentType, 0).getClass(); } - if(className.startsWith("L") && className.endsWith(";")){ + if (className.startsWith("L") && className.endsWith(";")) { String newClassName = className.substring(1, className.length() - 1); return loadClass(newClassName, classLoader); } - try{ - if(classLoader != null){ + try { + if (classLoader != null) { clazz = classLoader.loadClass(className); if (cache) { mappings.put(className, clazz); } return clazz; } - } catch(Throwable e){ + } catch (Throwable e) { e.printStackTrace(); // skip } - try{ + try { ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); - if(contextClassLoader != null && contextClassLoader != classLoader){ + if (contextClassLoader != null && contextClassLoader != classLoader) { clazz = contextClassLoader.loadClass(className); if (cache) { mappings.put(className, clazz); } return clazz; } - } catch(Throwable e){ + } catch (Throwable e) { // skip } - try{ + try { clazz = Class.forName(className); if (cache) { mappings.put(className, clazz); } return clazz; - } catch(Throwable e){ + } catch (Throwable e) { // skip } return clazz; } public static SerializeBeanInfo buildBeanInfo(Class beanType // - , Map aliasMap // - , PropertyNamingStrategy propertyNamingStrategy){ + , Map aliasMap // + , PropertyNamingStrategy propertyNamingStrategy) { return buildBeanInfo(beanType, aliasMap, propertyNamingStrategy, false); } public static SerializeBeanInfo buildBeanInfo(Class beanType // - , Map aliasMap // + , Map aliasMap // , PropertyNamingStrategy propertyNamingStrategy // , boolean fieldBased // - ){ - JSONType jsonType = TypeUtils.getAnnotation(beanType,JSONType.class); + ) { + JSONType jsonType = TypeUtils.getAnnotation(beanType, JSONType.class); String[] orders = null; final int features; String typeName = null, typeKey = null; - if(jsonType != null){ + if (jsonType != null) { orders = jsonType.orders(); typeName = jsonType.typeName(); - if(typeName.length() == 0){ + if (typeName.length() == 0) { typeName = null; } @@ -1783,37 +1820,37 @@ public class TypeUtils{ } features = SerializerFeature.of(jsonType.serialzeFeatures()); - for(Class supperClass = beanType.getSuperclass() - ; supperClass != null && supperClass != Object.class - ; supperClass = supperClass.getSuperclass()){ - JSONType superJsonType = TypeUtils.getAnnotation(supperClass,JSONType.class); - if(superJsonType == null){ + for (Class supperClass = beanType.getSuperclass() + ; supperClass != null && supperClass != Object.class + ; supperClass = supperClass.getSuperclass()) { + JSONType superJsonType = TypeUtils.getAnnotation(supperClass, JSONType.class); + if (superJsonType == null) { break; } typeKey = superJsonType.typeKey(); - if(typeKey.length() != 0){ + if (typeKey.length() != 0) { break; } } - for(Class interfaceClass : beanType.getInterfaces()){ - JSONType superJsonType = TypeUtils.getAnnotation(interfaceClass,JSONType.class); - if(superJsonType != null){ + for (Class interfaceClass : beanType.getInterfaces()) { + JSONType superJsonType = TypeUtils.getAnnotation(interfaceClass, JSONType.class); + if (superJsonType != null) { typeKey = superJsonType.typeKey(); - if(typeKey.length() != 0){ + if (typeKey.length() != 0) { break; } } } - if(typeKey != null && typeKey.length() == 0){ + if (typeKey != null && typeKey.length() == 0) { typeKey = null; } - } else{ + } else { features = 0; } // fieldName,field ,先生成fieldName的快照,减少之后的findField的轮询 - Map fieldCacheMap = new HashMap(); + Map fieldCacheMap = new HashMap(); ParserConfig.parserAllFieldToCache(beanType, fieldCacheMap); List fieldInfoList = fieldBased ? computeGettersWithFieldBase(beanType, aliasMap, false, propertyNamingStrategy) // @@ -1822,17 +1859,17 @@ public class TypeUtils{ fieldInfoList.toArray(fields); FieldInfo[] sortedFields; List sortedFieldList; - if(orders != null && orders.length != 0){ + if (orders != null && orders.length != 0) { sortedFieldList = fieldBased ? computeGettersWithFieldBase(beanType, aliasMap, true, propertyNamingStrategy) // : computeGetters(beanType, jsonType, aliasMap, fieldCacheMap, true, propertyNamingStrategy); - } else{ + } else { sortedFieldList = new ArrayList(fieldInfoList); Collections.sort(sortedFieldList); } sortedFields = new FieldInfo[sortedFieldList.size()]; sortedFieldList.toArray(sortedFields); - if(Arrays.equals(sortedFields, fields)){ + if (Arrays.equals(sortedFields, fields)) { sortedFields = fields; } return new SerializeBeanInfo(beanType, jsonType, typeName, typeKey, features, fields, sortedFields); @@ -1840,36 +1877,36 @@ public class TypeUtils{ public static List computeGettersWithFieldBase( Class clazz, // - Map aliasMap, // + Map aliasMap, // boolean sorted, // - PropertyNamingStrategy propertyNamingStrategy){ - Map fieldInfoMap = new LinkedHashMap(); - for(Class currentClass = clazz; currentClass != null; currentClass = currentClass.getSuperclass()){ + PropertyNamingStrategy propertyNamingStrategy) { + Map fieldInfoMap = new LinkedHashMap(); + for (Class currentClass = clazz; currentClass != null; currentClass = currentClass.getSuperclass()) { Field[] fields = currentClass.getDeclaredFields(); computeFields(currentClass, aliasMap, propertyNamingStrategy, fieldInfoMap, fields); } return getFieldInfos(clazz, sorted, fieldInfoMap); } - public static List computeGetters(Class clazz, Map aliasMap){ + public static List computeGetters(Class clazz, Map aliasMap) { return computeGetters(clazz, aliasMap, true); } - public static List computeGetters(Class clazz, Map aliasMap, boolean sorted){ - JSONType jsonType = TypeUtils.getAnnotation(clazz,JSONType.class); - Map fieldCacheMap = new HashMap(); + public static List computeGetters(Class clazz, Map aliasMap, boolean sorted) { + JSONType jsonType = TypeUtils.getAnnotation(clazz, JSONType.class); + Map fieldCacheMap = new HashMap(); ParserConfig.parserAllFieldToCache(clazz, fieldCacheMap); return computeGetters(clazz, jsonType, aliasMap, fieldCacheMap, sorted, PropertyNamingStrategy.CamelCase); } public static List computeGetters(Class clazz, // JSONType jsonType, // - Map aliasMap, // - Map fieldCacheMap, // + Map aliasMap, // + Map fieldCacheMap, // boolean sorted, // PropertyNamingStrategy propertyNamingStrategy // - ){ - Map fieldInfoMap = new LinkedHashMap(); + ) { + Map fieldInfoMap = new LinkedHashMap(); boolean kotlin = TypeUtils.isKotlin(clazz); // for kotlin Constructor[] constructors = null; @@ -1878,39 +1915,39 @@ public class TypeUtils{ short[] paramNameMapping = null; Method[] methods = clazz.getMethods(); Arrays.sort(methods, new MethodInheritanceComparator()); - for(Method method : methods){ + for (Method method : methods) { String methodName = method.getName(); int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0; String label = null; - if(Modifier.isStatic(method.getModifiers())){ + if (Modifier.isStatic(method.getModifiers())) { continue; } Class returnType = method.getReturnType(); - if(returnType.equals(Void.TYPE)){ + if (returnType.equals(Void.TYPE)) { continue; } - if(method.getParameterTypes().length != 0){ + if (method.getParameterTypes().length != 0) { continue; } - if(returnType == ClassLoader.class + if (returnType == ClassLoader.class || returnType == InputStream.class - || returnType == Reader.class){ + || returnType == Reader.class) { continue; } - if(methodName.equals("getMetaClass") - && returnType.getName().equals("groovy.lang.MetaClass")){ + if (methodName.equals("getMetaClass") + && returnType.getName().equals("groovy.lang.MetaClass")) { continue; } - if(methodName.equals("getSuppressed") - && method.getDeclaringClass() == Throwable.class){ + if (methodName.equals("getSuppressed") + && method.getDeclaringClass() == Throwable.class) { continue; } - if(kotlin && isKotlinIgnore(clazz, methodName)){ + if (kotlin && isKotlinIgnore(clazz, methodName)) { continue; } /** @@ -1918,23 +1955,23 @@ public class TypeUtils{ */ Boolean fieldAnnotationAndNameExists = false; JSONField annotation = TypeUtils.getAnnotation(method, JSONField.class); - if(annotation == null){ + if (annotation == null) { annotation = getSuperMethodAnnotation(clazz, method); } - if(annotation == null && kotlin){ - if(constructors == null){ + if (annotation == null && kotlin) { + if (constructors == null) { constructors = clazz.getDeclaredConstructors(); Constructor creatorConstructor = TypeUtils.getKotlinConstructor(constructors); - if(creatorConstructor != null){ + if (creatorConstructor != null) { paramAnnotationArrays = TypeUtils.getParameterAnnotations(creatorConstructor); paramNames = TypeUtils.getKoltinConstructorParameters(clazz); - if(paramNames != null){ + if (paramNames != null) { String[] paramNames_sorted = new String[paramNames.length]; System.arraycopy(paramNames, 0, paramNames_sorted, 0, paramNames.length); Arrays.sort(paramNames_sorted); paramNameMapping = new short[paramNames.length]; - for(short p = 0; p < paramNames.length; p++){ + for (short p = 0; p < paramNames.length; p++) { int index = Arrays.binarySearch(paramNames_sorted, paramNames[p]); paramNameMapping[index] = p; } @@ -1942,7 +1979,7 @@ public class TypeUtils{ } } } - if(paramNames != null && paramNameMapping != null && methodName.startsWith("get")){ + if (paramNames != null && paramNameMapping != null && methodName.startsWith("get")) { String propertyName = decapitalize(methodName.substring(3)); int p = Arrays.binarySearch(paramNames, propertyName); if (p < 0) { @@ -1953,38 +1990,38 @@ public class TypeUtils{ } } } - if(p >= 0){ + if (p >= 0) { short index = paramNameMapping[p]; Annotation[] paramAnnotations = paramAnnotationArrays[index]; - if(paramAnnotations != null){ - for(Annotation paramAnnotation : paramAnnotations){ - if(paramAnnotation instanceof JSONField){ + if (paramAnnotations != null) { + for (Annotation paramAnnotation : paramAnnotations) { + if (paramAnnotation instanceof JSONField) { annotation = (JSONField) paramAnnotation; break; } } } - if(annotation == null){ + if (annotation == null) { Field field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); - if(field != null){ + if (field != null) { annotation = TypeUtils.getAnnotation(field, JSONField.class); } } } } } - if(annotation != null){ - if(!annotation.serialize()){ + if (annotation != null) { + if (!annotation.serialize()) { continue; } ordinal = annotation.ordinal(); serialzeFeatures = SerializerFeature.of(annotation.serialzeFeatures()); parserFeatures = Feature.of(annotation.parseFeatures()); - if(annotation.name().length() != 0){ + if (annotation.name().length() != 0) { String propertyName = annotation.name(); - if(aliasMap != null){ + if (aliasMap != null) { propertyName = aliasMap.get(propertyName); - if(propertyName == null){ + if (propertyName == null) { continue; } } @@ -1993,33 +2030,33 @@ public class TypeUtils{ fieldInfoMap.put(propertyName, fieldInfo); continue; } - if(annotation.label().length() != 0){ + if (annotation.label().length() != 0) { label = annotation.label(); } } - if(methodName.startsWith("get")){ - if(methodName.length() < 4){ + if (methodName.startsWith("get")) { + if (methodName.length() < 4) { continue; } - if(methodName.equals("getClass")){ + if (methodName.equals("getClass")) { continue; } - if(methodName.equals("getDeclaringClass") && clazz.isEnum()){ + if (methodName.equals("getDeclaringClass") && clazz.isEnum()) { continue; } char c3 = methodName.charAt(3); String propertyName; Field field = null; - if(Character.isUpperCase(c3) // + if (Character.isUpperCase(c3) // || c3 > 512 // for unicode method name - ){ - if(compatibleWithJavaBean){ + ) { + if (compatibleWithJavaBean) { propertyName = decapitalize(methodName.substring(3)); - } else{ + } else { propertyName = TypeUtils.getPropertyNameByMethodName(methodName); } propertyName = getPropertyNameByCompatibleFieldName(fieldCacheMap, methodName, propertyName, 3); - } else if(c3 == '_'){ + } else if (c3 == '_') { propertyName = methodName.substring(3); field = fieldCacheMap.get(propertyName); if (field == null) { @@ -2030,11 +2067,11 @@ public class TypeUtils{ propertyName = temp; //减少修改代码带来的影响 } } - } else if(c3 == 'f'){ + } else if (c3 == 'f') { propertyName = methodName.substring(3); - } else if(methodName.length() >= 5 && Character.isUpperCase(methodName.charAt(4))){ + } else if (methodName.length() >= 5 && Character.isUpperCase(methodName.charAt(4))) { propertyName = decapitalize(methodName.substring(3)); - } else{ + } else { propertyName = methodName.substring(3); field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); if (field == null) { @@ -2042,7 +2079,7 @@ public class TypeUtils{ } } boolean ignore = isJSONTypeIgnore(clazz, propertyName); - if(ignore){ + if (ignore) { continue; } @@ -2051,70 +2088,70 @@ public class TypeUtils{ field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); } - if(field == null && propertyName.length() > 1){ + if (field == null && propertyName.length() > 1) { char ch = propertyName.charAt(1); - if(ch >= 'A' && ch <= 'Z'){ + if (ch >= 'A' && ch <= 'Z') { String javaBeanCompatiblePropertyName = decapitalize(methodName.substring(3)); field = ParserConfig.getFieldFromCache(javaBeanCompatiblePropertyName, fieldCacheMap); } } JSONField fieldAnnotation = null; - if(field != null){ + if (field != null) { fieldAnnotation = TypeUtils.getAnnotation(field, JSONField.class); - if(fieldAnnotation != null){ - if(!fieldAnnotation.serialize()){ + if (fieldAnnotation != null) { + if (!fieldAnnotation.serialize()) { continue; } ordinal = fieldAnnotation.ordinal(); serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); - if(fieldAnnotation.name().length() != 0){ + if (fieldAnnotation.name().length() != 0) { fieldAnnotationAndNameExists = true; propertyName = fieldAnnotation.name(); - if(aliasMap != null){ + if (aliasMap != null) { propertyName = aliasMap.get(propertyName); - if(propertyName == null){ + if (propertyName == null) { continue; } } } - if(fieldAnnotation.label().length() != 0){ + if (fieldAnnotation.label().length() != 0) { label = fieldAnnotation.label(); } } } - if(aliasMap != null){ + if (aliasMap != null) { propertyName = aliasMap.get(propertyName); - if(propertyName == null){ + if (propertyName == null) { continue; } } - if(propertyNamingStrategy != null && !fieldAnnotationAndNameExists){ + if (propertyNamingStrategy != null && !fieldAnnotationAndNameExists) { propertyName = propertyNamingStrategy.translate(propertyName); } FieldInfo fieldInfo = new FieldInfo(propertyName, method, field, clazz, null, ordinal, serialzeFeatures, parserFeatures, annotation, fieldAnnotation, label); fieldInfoMap.put(propertyName, fieldInfo); } - if(methodName.startsWith("is")){ - if(methodName.length() < 3){ + if (methodName.startsWith("is")) { + if (methodName.length() < 3) { continue; } - if(returnType != Boolean.TYPE - && returnType != Boolean.class){ + if (returnType != Boolean.TYPE + && returnType != Boolean.class) { continue; } char c2 = methodName.charAt(2); String propertyName; Field field = null; - if(Character.isUpperCase(c2)){ - if(compatibleWithJavaBean){ + if (Character.isUpperCase(c2)) { + if (compatibleWithJavaBean) { propertyName = decapitalize(methodName.substring(2)); - } else{ + } else { propertyName = Character.toLowerCase(methodName.charAt(2)) + methodName.substring(3); } propertyName = getPropertyNameByCompatibleFieldName(fieldCacheMap, methodName, propertyName, 2); - } else if(c2 == '_'){ + } else if (c2 == '_') { propertyName = methodName.substring(3); field = fieldCacheMap.get(propertyName); if (field == null) { @@ -2125,9 +2162,9 @@ public class TypeUtils{ propertyName = temp; } } - } else if(c2 == 'f'){ + } else if (c2 == 'f') { propertyName = methodName.substring(2); - } else{ + } else { propertyName = methodName.substring(2); field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); if (field == null) { @@ -2135,52 +2172,52 @@ public class TypeUtils{ } } boolean ignore = isJSONTypeIgnore(clazz, propertyName); - if(ignore){ + if (ignore) { continue; } - if(field == null) { + if (field == null) { field = ParserConfig.getFieldFromCache(propertyName, fieldCacheMap); } - if(field == null){ + if (field == null) { field = ParserConfig.getFieldFromCache(methodName, fieldCacheMap); } JSONField fieldAnnotation = null; - if(field != null){ + if (field != null) { fieldAnnotation = TypeUtils.getAnnotation(field, JSONField.class); - if(fieldAnnotation != null){ - if(!fieldAnnotation.serialize()){ + if (fieldAnnotation != null) { + if (!fieldAnnotation.serialize()) { continue; } ordinal = fieldAnnotation.ordinal(); serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); - if(fieldAnnotation.name().length() != 0){ + if (fieldAnnotation.name().length() != 0) { propertyName = fieldAnnotation.name(); - if(aliasMap != null){ + if (aliasMap != null) { propertyName = aliasMap.get(propertyName); - if(propertyName == null){ + if (propertyName == null) { continue; } } } - if(fieldAnnotation.label().length() != 0){ + if (fieldAnnotation.label().length() != 0) { label = fieldAnnotation.label(); } } } - if(aliasMap != null){ + if (aliasMap != null) { propertyName = aliasMap.get(propertyName); - if(propertyName == null){ + if (propertyName == null) { continue; } } - if(propertyNamingStrategy != null){ + if (propertyNamingStrategy != null) { propertyName = propertyNamingStrategy.translate(propertyName); } //优先选择get - if(fieldInfoMap.containsKey(propertyName)){ + if (fieldInfoMap.containsKey(propertyName)) { continue; } FieldInfo fieldInfo = new FieldInfo(propertyName, method, field, clazz, null, ordinal, serialzeFeatures, parserFeatures, @@ -2193,29 +2230,29 @@ public class TypeUtils{ return getFieldInfos(clazz, sorted, fieldInfoMap); } - private static List getFieldInfos(Class clazz, boolean sorted, Map fieldInfoMap){ + private static List getFieldInfos(Class clazz, boolean sorted, Map fieldInfoMap) { List fieldInfoList = new ArrayList(); String[] orders = null; - JSONType annotation = TypeUtils.getAnnotation(clazz,JSONType.class); - if(annotation != null){ + JSONType annotation = TypeUtils.getAnnotation(clazz, JSONType.class); + if (annotation != null) { orders = annotation.orders(); } - if(orders != null && orders.length > 0){ - LinkedHashMap map = new LinkedHashMap(fieldInfoMap.size()); - for(FieldInfo field : fieldInfoMap.values()){ + if (orders != null && orders.length > 0) { + LinkedHashMap map = new LinkedHashMap(fieldInfoMap.size()); + for (FieldInfo field : fieldInfoMap.values()) { map.put(field.name, field); } - for(String item : orders){ + for (String item : orders) { FieldInfo field = map.get(item); - if(field != null){ + if (field != null) { fieldInfoList.add(field); map.remove(item); } } fieldInfoList.addAll(map.values()); - } else{ + } else { fieldInfoList.addAll(fieldInfoMap.values()); - if(sorted){ + if (sorted) { Collections.sort(fieldInfoList); } } @@ -2224,42 +2261,42 @@ public class TypeUtils{ private static void computeFields( Class clazz, // - Map aliasMap, // + Map aliasMap, // PropertyNamingStrategy propertyNamingStrategy, // - Map fieldInfoMap, // - Field[] fields){ - for(Field field : fields){ - if(Modifier.isStatic(field.getModifiers())){ + Map fieldInfoMap, // + Field[] fields) { + for (Field field : fields) { + if (Modifier.isStatic(field.getModifiers())) { continue; } JSONField fieldAnnotation = TypeUtils.getAnnotation(field, JSONField.class); int ordinal = 0, serialzeFeatures = 0, parserFeatures = 0; String propertyName = field.getName(); String label = null; - if(fieldAnnotation != null){ - if(!fieldAnnotation.serialize()){ + if (fieldAnnotation != null) { + if (!fieldAnnotation.serialize()) { continue; } ordinal = fieldAnnotation.ordinal(); serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures()); parserFeatures = Feature.of(fieldAnnotation.parseFeatures()); - if(fieldAnnotation.name().length() != 0){ + if (fieldAnnotation.name().length() != 0) { propertyName = fieldAnnotation.name(); } - if(fieldAnnotation.label().length() != 0){ + if (fieldAnnotation.label().length() != 0) { label = fieldAnnotation.label(); } } - if(aliasMap != null){ + if (aliasMap != null) { propertyName = aliasMap.get(propertyName); - if(propertyName == null){ + if (propertyName == null) { continue; } } - if(propertyNamingStrategy != null){ + if (propertyNamingStrategy != null) { propertyName = propertyNamingStrategy.translate(propertyName); } - if(!fieldInfoMap.containsKey(propertyName)){ + if (!fieldInfoMap.containsKey(propertyName)) { FieldInfo fieldInfo = new FieldInfo(propertyName, null, field, clazz, null, ordinal, serialzeFeatures, parserFeatures, null, fieldAnnotation, label); fieldInfoMap.put(propertyName, fieldInfo); @@ -2267,10 +2304,10 @@ public class TypeUtils{ } } - private static String getPropertyNameByCompatibleFieldName(Map fieldCacheMap, String methodName, - String propertyName, int fromIdx){ - if(compatibleWithFieldName){ - if(!fieldCacheMap.containsKey(propertyName)){ + private static String getPropertyNameByCompatibleFieldName(Map fieldCacheMap, String methodName, + String propertyName, int fromIdx) { + if (compatibleWithFieldName) { + if (!fieldCacheMap.containsKey(propertyName)) { String tempPropertyName = methodName.substring(fromIdx); return fieldCacheMap.containsKey(tempPropertyName) ? tempPropertyName : propertyName; } @@ -2278,62 +2315,62 @@ public class TypeUtils{ return propertyName; } - public static JSONField getSuperMethodAnnotation(final Class clazz, final Method method){ + public static JSONField getSuperMethodAnnotation(final Class clazz, final Method method) { Class[] interfaces = clazz.getInterfaces(); - if(interfaces.length > 0){ + if (interfaces.length > 0) { Class[] types = method.getParameterTypes(); - for(Class interfaceClass : interfaces){ - for(Method interfaceMethod : interfaceClass.getMethods()){ + for (Class interfaceClass : interfaces) { + for (Method interfaceMethod : interfaceClass.getMethods()) { Class[] interfaceTypes = interfaceMethod.getParameterTypes(); - if(interfaceTypes.length != types.length){ + if (interfaceTypes.length != types.length) { continue; } - if(!interfaceMethod.getName().equals(method.getName())){ + if (!interfaceMethod.getName().equals(method.getName())) { continue; } boolean match = true; - for(int i = 0; i < types.length; ++i){ - if(!interfaceTypes[i].equals(types[i])){ + for (int i = 0; i < types.length; ++i) { + if (!interfaceTypes[i].equals(types[i])) { match = false; break; } } - if(!match){ + if (!match) { continue; } JSONField annotation = TypeUtils.getAnnotation(interfaceMethod, JSONField.class); - if(annotation != null){ + if (annotation != null) { return annotation; } } } } Class superClass = clazz.getSuperclass(); - if(superClass == null){ + if (superClass == null) { return null; } - if(Modifier.isAbstract(superClass.getModifiers())){ + if (Modifier.isAbstract(superClass.getModifiers())) { Class[] types = method.getParameterTypes(); - for(Method interfaceMethod : superClass.getMethods()){ + for (Method interfaceMethod : superClass.getMethods()) { Class[] interfaceTypes = interfaceMethod.getParameterTypes(); - if(interfaceTypes.length != types.length){ + if (interfaceTypes.length != types.length) { continue; } - if(!interfaceMethod.getName().equals(method.getName())){ + if (!interfaceMethod.getName().equals(method.getName())) { continue; } boolean match = true; - for(int i = 0; i < types.length; ++i){ - if(!interfaceTypes[i].equals(types[i])){ + for (int i = 0; i < types.length; ++i) { + if (!interfaceTypes[i].equals(types[i])) { match = false; break; } } - if(!match){ + if (!match) { continue; } JSONField annotation = TypeUtils.getAnnotation(interfaceMethod, JSONField.class); - if(annotation != null){ + if (annotation != null) { return annotation; } } @@ -2341,21 +2378,21 @@ public class TypeUtils{ return null; } - private static boolean isJSONTypeIgnore(Class clazz, String propertyName){ - JSONType jsonType = TypeUtils.getAnnotation(clazz,JSONType.class); - if(jsonType != null){ + private static boolean isJSONTypeIgnore(Class clazz, String propertyName) { + JSONType jsonType = TypeUtils.getAnnotation(clazz, JSONType.class); + if (jsonType != null) { // 1、新增 includes 支持,如果 JSONType 同时设置了includes 和 ignores 属性,则以includes为准。 // 2、个人认为对于大小写敏感的Java和JS而言,使用 equals() 比 equalsIgnoreCase() 更好,改动的唯一风险就是向后兼容性的问题 // 不过,相信开发者应该都是严格按照大小写敏感的方式进行属性设置的 String[] fields = jsonType.includes(); - if(fields.length > 0){ + if (fields.length > 0) { for (String field : fields) { if (propertyName.equals(field)) { return false; } } return true; - } else{ + } else { fields = jsonType.ignores(); for (String field : fields) { if (propertyName.equals(field)) { @@ -2364,62 +2401,62 @@ public class TypeUtils{ } } } - if(clazz.getSuperclass() != Object.class && clazz.getSuperclass() != null){ + if (clazz.getSuperclass() != Object.class && clazz.getSuperclass() != null) { return isJSONTypeIgnore(clazz.getSuperclass(), propertyName); } return false; } - public static boolean isGenericParamType(Type type){ - if(type instanceof ParameterizedType){ + public static boolean isGenericParamType(Type type) { + if (type instanceof ParameterizedType) { return true; } - if(type instanceof Class) { + if (type instanceof Class) { Type superType = ((Class) type).getGenericSuperclass(); return superType != Object.class && isGenericParamType(superType); } return false; } - public static Type getGenericParamType(Type type){ - if(type instanceof ParameterizedType){ + public static Type getGenericParamType(Type type) { + if (type instanceof ParameterizedType) { return type; } - if(type instanceof Class){ + if (type instanceof Class) { return getGenericParamType(((Class) type).getGenericSuperclass()); } return type; } - public static Type unwrapOptional(Type type){ - if(!optionalClassInited){ - try{ + public static Type unwrapOptional(Type type) { + if (!optionalClassInited) { + try { optionalClass = Class.forName("java.util.Optional"); - } catch(Exception e){ + } catch (Exception e) { // skip - } finally{ + } finally { optionalClassInited = true; } } - if(type instanceof ParameterizedType){ + if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; - if(parameterizedType.getRawType() == optionalClass){ + if (parameterizedType.getRawType() == optionalClass) { return parameterizedType.getActualTypeArguments()[0]; } } return type; } - public static Class getClass(Type type){ - if(type.getClass() == Class.class){ + public static Class getClass(Type type) { + if (type.getClass() == Class.class) { return (Class) type; } - if(type instanceof ParameterizedType){ + if (type instanceof ParameterizedType) { return getClass(((ParameterizedType) type).getRawType()); } - if(type instanceof TypeVariable){ + if (type instanceof TypeVariable) { Type boundType = ((TypeVariable) type).getBounds()[0]; if (boundType instanceof Class) { return (Class) boundType; @@ -2427,7 +2464,7 @@ public class TypeUtils{ return getClass(boundType); } - if(type instanceof WildcardType){ + if (type instanceof WildcardType) { Type[] upperBounds = ((WildcardType) type).getUpperBounds(); if (upperBounds.length == 1) { return getClass(upperBounds[0]); @@ -2437,10 +2474,10 @@ public class TypeUtils{ return Object.class; } - public static Field getField(Class clazz, String fieldName, Field[] declaredFields){ - for(Field field : declaredFields){ + public static Field getField(Class clazz, String fieldName, Field[] declaredFields) { + for (Field field : declaredFields) { String itemName = field.getName(); - if(fieldName.equals(itemName)){ + if (fieldName.equals(itemName)) { return field; } @@ -2453,7 +2490,7 @@ public class TypeUtils{ } } Class superClass = clazz.getSuperclass(); - if(superClass != null && superClass != Object.class){ + if (superClass != null && superClass != Object.class) { return getField(superClass, fieldName, superClass.getDeclaredFields()); } return null; @@ -2462,27 +2499,27 @@ public class TypeUtils{ /** * @deprecated */ - public static int getSerializeFeatures(Class clazz){ - JSONType annotation = TypeUtils.getAnnotation(clazz,JSONType.class); - if(annotation == null){ + public static int getSerializeFeatures(Class clazz) { + JSONType annotation = TypeUtils.getAnnotation(clazz, JSONType.class); + if (annotation == null) { return 0; } return SerializerFeature.of(annotation.serialzeFeatures()); } - public static int getParserFeatures(Class clazz){ - JSONType annotation = TypeUtils.getAnnotation(clazz,JSONType.class); - if(annotation == null){ + public static int getParserFeatures(Class clazz) { + JSONType annotation = TypeUtils.getAnnotation(clazz, JSONType.class); + if (annotation == null) { return 0; } return Feature.of(annotation.parseFeatures()); } - public static String decapitalize(String name){ - if(name == null || name.length() == 0){ + public static String decapitalize(String name) { + if (name == null || name.length() == 0) { return name; } - if(name.length() > 1 && Character.isUpperCase(name.charAt(1)) && Character.isUpperCase(name.charAt(0))){ + if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) && Character.isUpperCase(name.charAt(0))) { return name; } char[] chars = name.toCharArray(); @@ -2500,16 +2537,16 @@ public class TypeUtils{ return Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); } - static void setAccessible(AccessibleObject obj){ - if(!setAccessibleEnable){ + static void setAccessible(AccessibleObject obj) { + if (!setAccessibleEnable) { return; } - if(obj.isAccessible()){ + if (obj.isAccessible()) { return; } - try{ + try { obj.setAccessible(true); - } catch(AccessControlException error){ + } catch (AccessControlException error) { setAccessibleEnable = false; } } @@ -2601,42 +2638,44 @@ public class TypeUtils{ return type; } - public static Class getCollectionItemClass(Type fieldType){ - if(fieldType instanceof ParameterizedType){ + public static Class getCollectionItemClass(Type fieldType) { + if (fieldType instanceof ParameterizedType) { Class itemClass; Type actualTypeArgument = ((ParameterizedType) fieldType).getActualTypeArguments()[0]; - if(actualTypeArgument instanceof WildcardType){ + if (actualTypeArgument instanceof WildcardType) { WildcardType wildcardType = (WildcardType) actualTypeArgument; Type[] upperBounds = wildcardType.getUpperBounds(); - if(upperBounds.length == 1){ + if (upperBounds.length == 1) { actualTypeArgument = upperBounds[0]; } } - if(actualTypeArgument instanceof Class){ + if (actualTypeArgument instanceof Class) { itemClass = (Class) actualTypeArgument; - if(!Modifier.isPublic(itemClass.getModifiers())){ + if (!Modifier.isPublic(itemClass.getModifiers())) { throw new JSONException("can not create ASMParser"); } - } else{ + } else { throw new JSONException("can not create ASMParser"); } return itemClass; } return Object.class; } - private static final Map primitiveTypeMap = new HashMap(8){{ - put(boolean.class,"Z"); - put(char.class,"C"); - put(byte.class,"B"); - put(short.class,"S"); - put(int.class,"I"); - put(long.class,"J"); - put(float.class,"F"); - put(double.class,"D"); + + private static final Map primitiveTypeMap = new HashMap(8) {{ + put(boolean.class, "Z"); + put(char.class, "C"); + put(byte.class, "B"); + put(short.class, "S"); + put(int.class, "I"); + put(long.class, "J"); + put(float.class, "F"); + put(double.class, "D"); }}; + public static Type checkPrimitiveArray(GenericArrayType genericArrayType) { Type clz = genericArrayType; - Type genericComponentType = genericArrayType.getGenericComponentType(); + Type genericComponentType = genericArrayType.getGenericComponentType(); String prefix = "["; while (genericComponentType instanceof GenericArrayType) { @@ -2650,8 +2689,8 @@ public class TypeUtils{ if (ck.isPrimitive()) { try { String postfix = (String) primitiveTypeMap.get(ck); - if(postfix != null){ - clz = Class.forName(prefix+postfix); + if (postfix != null) { + clz = Class.forName(prefix + postfix); } } catch (ClassNotFoundException ignored) { } @@ -2665,7 +2704,7 @@ public class TypeUtils{ public static Collection createCollection(Type type) { Class rawClass = getRawClass(type); Collection list; - if(rawClass == AbstractCollection.class // + if (rawClass == AbstractCollection.class // || rawClass == Collection.class) { list = new ArrayList(); } else if (rawClass.isAssignableFrom(HashSet.class)) { @@ -2674,23 +2713,23 @@ public class TypeUtils{ list = new LinkedHashSet(); } else if (rawClass.isAssignableFrom(TreeSet.class)) { list = new TreeSet(); - } else if(rawClass.isAssignableFrom(ArrayList.class)) { + } else if (rawClass.isAssignableFrom(ArrayList.class)) { list = new ArrayList(); } else if (rawClass.isAssignableFrom(EnumSet.class)) { Type itemType; - if(type instanceof ParameterizedType){ + if (type instanceof ParameterizedType) { itemType = ((ParameterizedType) type).getActualTypeArguments()[0]; } else { itemType = Object.class; } list = EnumSet.noneOf((Class) itemType); } else if (rawClass.isAssignableFrom(Queue.class) - || (class_deque != null && rawClass.isAssignableFrom(class_deque))){ + || (class_deque != null && rawClass.isAssignableFrom(class_deque))) { list = new LinkedList(); } else { try { list = (Collection) rawClass.newInstance(); - } catch(Exception e) { + } catch (Exception e) { throw new JSONException("create instance error, class " + rawClass.getName()); } } @@ -2698,11 +2737,11 @@ public class TypeUtils{ } public static Class getRawClass(Type type) { - if(type instanceof Class){ + if (type instanceof Class) { return (Class) type; - } else if(type instanceof ParameterizedType) { - return getRawClass(((ParameterizedType)type).getRawType()); - } else if(type instanceof WildcardType) { + } else if (type instanceof ParameterizedType) { + return getRawClass(((ParameterizedType) type).getRawType()); + } else if (type instanceof WildcardType) { WildcardType wildcardType = (WildcardType) type; Type[] upperBounds = wildcardType.getUpperBounds(); if (upperBounds.length == 1) { @@ -2710,12 +2749,12 @@ public class TypeUtils{ } else { throw new JSONException("TODO"); } - } else{ + } else { throw new JSONException("TODO"); } } - private static final Set isProxyClassNames = new HashSet(6){{ + private static final Set isProxyClassNames = new HashSet(6) {{ add("net.sf.cglib.proxy.Factory"); add("org.springframework.cglib.proxy.Factory"); add("javassist.util.proxy.ProxyObject"); @@ -2723,31 +2762,32 @@ public class TypeUtils{ add("org.hibernate.proxy.HibernateProxy"); add("org.springframework.context.annotation.ConfigurationClassEnhancer$EnhancedConfiguration"); }}; - public static boolean isProxy(Class clazz){ - for(Class item : clazz.getInterfaces()){ + public static boolean isProxy(Class clazz) { + + for (Class item : clazz.getInterfaces()) { String interfaceName = item.getName(); - if (isProxyClassNames.contains(interfaceName)){ + if (isProxyClassNames.contains(interfaceName)) { return true; } } return false; } - public static boolean isTransient(Method method){ - if(method == null){ + public static boolean isTransient(Method method) { + if (method == null) { return false; } - if(!transientClassInited){ - try{ + if (!transientClassInited) { + try { transientClass = (Class) Class.forName("java.beans.Transient"); - } catch(Exception e){ + } catch (Exception e) { // skip - } finally{ + } finally { transientClassInited = true; } } - if(transientClass != null){ + if (transientClass != null) { Annotation annotation = TypeUtils.getAnnotation(method, transientClass); return annotation != null; } @@ -2788,24 +2828,24 @@ public class TypeUtils{ } - public static boolean isHibernateInitialized(Object object){ - if(object == null){ + public static boolean isHibernateInitialized(Object object) { + if (object == null) { return false; } - if(method_HibernateIsInitialized == null && !method_HibernateIsInitialized_error){ - try{ + if (method_HibernateIsInitialized == null && !method_HibernateIsInitialized_error) { + try { Class class_Hibernate = Class.forName("org.hibernate.Hibernate"); method_HibernateIsInitialized = class_Hibernate.getMethod("isInitialized", Object.class); - } catch(Throwable e){ + } catch (Throwable e) { // skip method_HibernateIsInitialized_error = true; } } - if(method_HibernateIsInitialized != null){ - try{ + if (method_HibernateIsInitialized != null) { + try { Boolean initialized = (Boolean) method_HibernateIsInitialized.invoke(null, object); return initialized; - } catch(Throwable e){ + } catch (Throwable e) { // skip } } @@ -2937,17 +2977,18 @@ public class TypeUtils{ return Float.parseFloat(str); } + public static final long fnv1a_64_magic_hashcode = 0xcbf29ce484222325L; public static final long fnv1a_64_magic_prime = 0x100000001b3L; - public static long fnv1a_64_extract(String key){ + public static long fnv1a_64_extract(String key) { long hashCode = fnv1a_64_magic_hashcode; - for(int i = 0; i < key.length(); ++i){ + for (int i = 0; i < key.length(); ++i) { char ch = key.charAt(i); - if(ch == '_' || ch == '-'){ + if (ch == '_' || ch == '-') { continue; } - if(ch >= 'A' && ch <= 'Z'){ + if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; @@ -2956,11 +2997,11 @@ public class TypeUtils{ return hashCode; } - public static long fnv1a_64_lower(String key){ + public static long fnv1a_64_lower(String key) { long hashCode = fnv1a_64_magic_hashcode; - for(int i = 0; i < key.length(); ++i){ + for (int i = 0; i < key.length(); ++i) { char ch = key.charAt(i); - if(ch >= 'A' && ch <= 'Z'){ + if (ch >= 'A' && ch <= 'Z') { ch = (char) (ch + 32); } hashCode ^= ch; @@ -2968,9 +3009,10 @@ public class TypeUtils{ } return hashCode; } - public static long fnv1a_64(String key){ + + public static long fnv1a_64(String key) { long hashCode = fnv1a_64_magic_hashcode; - for(int i = 0; i < key.length(); ++i){ + for (int i = 0; i < key.length(); ++i) { char ch = key.charAt(i); hashCode ^= ch; hashCode *= fnv1a_64_magic_prime; @@ -2989,22 +3031,22 @@ public class TypeUtils{ return kotlin_metadata != null && clazz.isAnnotationPresent(kotlin_metadata); } - public static Constructor getKotlinConstructor(Constructor[] constructors){ + public static Constructor getKotlinConstructor(Constructor[] constructors) { return getKotlinConstructor(constructors, null); } - public static Constructor getKotlinConstructor(Constructor[] constructors, String[] paramNames){ + public static Constructor getKotlinConstructor(Constructor[] constructors, String[] paramNames) { Constructor creatorConstructor = null; - for(Constructor constructor : constructors){ + for (Constructor constructor : constructors) { Class[] parameterTypes = constructor.getParameterTypes(); if (paramNames != null && parameterTypes.length != paramNames.length) { continue; } - if(parameterTypes.length > 0 && parameterTypes[parameterTypes.length - 1].getName().equals("kotlin.jvm.internal.DefaultConstructorMarker")){ + if (parameterTypes.length > 0 && parameterTypes[parameterTypes.length - 1].getName().equals("kotlin.jvm.internal.DefaultConstructorMarker")) { continue; } - if(creatorConstructor != null && creatorConstructor.getParameterTypes().length >= parameterTypes.length){ + if (creatorConstructor != null && creatorConstructor.getParameterTypes().length >= parameterTypes.length) { continue; } creatorConstructor = constructor; @@ -3012,55 +3054,55 @@ public class TypeUtils{ return creatorConstructor; } - public static String[] getKoltinConstructorParameters(Class clazz){ - if(kotlin_kclass_constructor == null && !kotlin_class_klass_error){ - try{ + public static String[] getKoltinConstructorParameters(Class clazz) { + if (kotlin_kclass_constructor == null && !kotlin_class_klass_error) { + try { Class class_kotlin_kclass = Class.forName("kotlin.reflect.jvm.internal.KClassImpl"); kotlin_kclass_constructor = class_kotlin_kclass.getConstructor(Class.class); - } catch(Throwable e){ + } catch (Throwable e) { kotlin_class_klass_error = true; } } - if (kotlin_kclass_constructor == null){ + if (kotlin_kclass_constructor == null) { return null; } if (kotlin_kclass_getConstructors == null && !kotlin_class_klass_error) { - try{ + try { Class class_kotlin_kclass = Class.forName("kotlin.reflect.jvm.internal.KClassImpl"); kotlin_kclass_getConstructors = class_kotlin_kclass.getMethod("getConstructors"); - } catch(Throwable e){ + } catch (Throwable e) { kotlin_class_klass_error = true; } } if (kotlin_kfunction_getParameters == null && !kotlin_class_klass_error) { - try{ + try { Class class_kotlin_kfunction = Class.forName("kotlin.reflect.KFunction"); kotlin_kfunction_getParameters = class_kotlin_kfunction.getMethod("getParameters"); - } catch(Throwable e){ + } catch (Throwable e) { kotlin_class_klass_error = true; } } if (kotlin_kparameter_getName == null && !kotlin_class_klass_error) { - try{ + try { Class class_kotlinn_kparameter = Class.forName("kotlin.reflect.KParameter"); kotlin_kparameter_getName = class_kotlinn_kparameter.getMethod("getName"); - } catch(Throwable e){ + } catch (Throwable e) { kotlin_class_klass_error = true; } } - if (kotlin_error){ + if (kotlin_error) { return null; } - try{ + try { Object constructor = null; Object kclassImpl = kotlin_kclass_constructor.newInstance(clazz); Iterable it = (Iterable) kotlin_kclass_getConstructors.invoke(kclassImpl); - for(Iterator iterator = it.iterator(); iterator.hasNext(); iterator.hasNext()){ + for (Iterator iterator = it.iterator(); iterator.hasNext(); iterator.hasNext()) { Object item = iterator.next(); List parameters = (List) kotlin_kfunction_getParameters.invoke(item); if (constructor != null && parameters.size() == 0) { @@ -3075,12 +3117,12 @@ public class TypeUtils{ List parameters = (List) kotlin_kfunction_getParameters.invoke(constructor); String[] names = new String[parameters.size()]; - for(int i = 0; i < parameters.size(); i++){ + for (int i = 0; i < parameters.size(); i++) { Object param = parameters.get(i); names[i] = (String) kotlin_kparameter_getName.invoke(param); } return names; - } catch(Throwable e){ + } catch (Throwable e) { e.printStackTrace(); kotlin_error = true; } @@ -3113,7 +3155,7 @@ public class TypeUtils{ return ignores != null && Arrays.binarySearch(ignores, methodName) >= 0; } - public static A getAnnotation(Class targetClass, Class annotationClass){ + public static A getAnnotation(Class targetClass, Class annotationClass) { A targetAnnotation = targetClass.getAnnotation(annotationClass); Class mixInClass = null; @@ -3122,13 +3164,13 @@ public class TypeUtils{ mixInClass = (Class) type; } - if(mixInClass != null) { + if (mixInClass != null) { A mixInAnnotation = mixInClass.getAnnotation(annotationClass); Annotation[] annotations = mixInClass.getAnnotations(); - if(mixInAnnotation == null && annotations.length > 0){ - for(Annotation annotation : annotations){ + if (mixInAnnotation == null && annotations.length > 0) { + for (Annotation annotation : annotations) { mixInAnnotation = annotation.annotationType().getAnnotation(annotationClass); - if(mixInAnnotation != null){ + if (mixInAnnotation != null) { break; } } @@ -3139,10 +3181,10 @@ public class TypeUtils{ } Annotation[] targetClassAnnotations = targetClass.getAnnotations(); - if(targetAnnotation == null && targetClassAnnotations.length > 0){ - for(Annotation annotation : targetClassAnnotations){ + if (targetAnnotation == null && targetClassAnnotations.length > 0) { + for (Annotation annotation : targetClassAnnotations) { targetAnnotation = annotation.annotationType().getAnnotation(annotationClass); - if(targetAnnotation != null){ + if (targetAnnotation != null) { break; } } @@ -3150,7 +3192,7 @@ public class TypeUtils{ return targetAnnotation; } - public static A getAnnotation(Field field, Class annotationClass){ + public static A getAnnotation(Field field, Class annotationClass) { A targetAnnotation = field.getAnnotation(annotationClass); Class clazz = field.getDeclaringClass(); @@ -3185,7 +3227,7 @@ public class TypeUtils{ return targetAnnotation; } - public static A getAnnotation(Method method, Class annotationClass){ + public static A getAnnotation(Method method, Class annotationClass) { A targetAnnotation = method.getAnnotation(annotationClass); Class clazz = method.getDeclaringClass(); @@ -3221,7 +3263,7 @@ public class TypeUtils{ return targetAnnotation; } - public static Annotation[][] getParameterAnnotations(Method method){ + public static Annotation[][] getParameterAnnotations(Method method) { Annotation[][] targetAnnotations = method.getParameterAnnotations(); Class clazz = method.getDeclaringClass(); @@ -3257,7 +3299,7 @@ public class TypeUtils{ return targetAnnotations; } - public static Annotation[][] getParameterAnnotations(Constructor constructor){ + public static Annotation[][] getParameterAnnotations(Constructor constructor) { Annotation[][] targetAnnotations = constructor.getParameterAnnotations(); Class clazz = constructor.getDeclaringClass(); @@ -3284,7 +3326,7 @@ public class TypeUtils{ if (level != 0) { Class[] outerClassAndParameterTypes = new Class[level + parameterTypes.length]; System.arraycopy(parameterTypes, 0, outerClassAndParameterTypes, level, parameterTypes.length); - for (int i = level; i > 0 ; i--) { + for (int i = level; i > 0; i--) { outerClassAndParameterTypes[i - 1] = enclosingClasses.get(i - 1); } mixInConstructor = mixInClass.getDeclaredConstructor(outerClassAndParameterTypes); @@ -3325,6 +3367,7 @@ public class TypeUtils{ private static Object OPTIONAL_EMPTY; private static boolean OPTIONAL_ERROR = false; + public static Object optionalEmpty(Type type) { if (OPTIONAL_ERROR) { return null; @@ -3350,6 +3393,7 @@ public class TypeUtils{ } return null; } + public static class MethodInheritanceComparator implements Comparator { public int compare(Method m1, Method m2) { Class class1 = m1.getReturnType();