diff --git a/codegen/src/main/java/com/alibaba/fastjson2/internal/processor/Analysis.java b/codegen/src/main/java/com/alibaba/fastjson2/internal/processor/Analysis.java index 465c32ac75..80e93ce22b 100644 --- a/codegen/src/main/java/com/alibaba/fastjson2/internal/processor/Analysis.java +++ b/codegen/src/main/java/com/alibaba/fastjson2/internal/processor/Analysis.java @@ -168,9 +168,9 @@ private void findRelatedReferences() { } ExecutableElement getter = null, setter = null; - TypeMirror type = null; - String name = null; - if (parameters.size() == 0 && (methodName.startsWith("get") || methodName.startsWith("is"))) { + TypeMirror type; + String name; + if (parameters.isEmpty() && (methodName.startsWith("get") || methodName.startsWith("is"))) { name = BeanUtils.getterName(methodName, null); getter = method; type = method.getReturnType(); @@ -188,8 +188,8 @@ private void findRelatedReferences() { } private List getTypeHierarchy(TypeElement element) { - List result = new ArrayList(); - getAllTypes(element, result, new HashSet()); + List result = new ArrayList<>(); + getAllTypes(element, result, new HashSet<>()); return result; } diff --git a/codegen/src/main/java/com/alibaba/fastjson2/internal/processor/CodeGenUtils.java b/codegen/src/main/java/com/alibaba/fastjson2/internal/processor/CodeGenUtils.java index dfe41a881e..2967c71527 100644 --- a/codegen/src/main/java/com/alibaba/fastjson2/internal/processor/CodeGenUtils.java +++ b/codegen/src/main/java/com/alibaba/fastjson2/internal/processor/CodeGenUtils.java @@ -495,7 +495,7 @@ public static void getFieldInfo(FieldInfo fieldInfo, JSONField jsonField, boolea if (!jsonFieldFormat.isEmpty()) { jsonFieldFormat = jsonFieldFormat.trim(); if (jsonFieldFormat.indexOf('T') != -1 && !jsonFieldFormat.contains("'T'")) { - jsonFieldFormat = jsonFieldFormat.replaceAll("T", "'T'"); + jsonFieldFormat = jsonFieldFormat.replace("T", "'T'"); } fieldInfo.format = jsonFieldFormat; diff --git a/core/src/main/java/com/alibaba/fastjson2/JSONPathSegment.java b/core/src/main/java/com/alibaba/fastjson2/JSONPathSegment.java index bcfcd47a66..1127990b4a 100644 --- a/core/src/main/java/com/alibaba/fastjson2/JSONPathSegment.java +++ b/core/src/main/java/com/alibaba/fastjson2/JSONPathSegment.java @@ -1410,7 +1410,7 @@ public void setCallback(JSONPath.Context context, BiFunction callback) { action.accept(object); } - protected boolean shouldRecursive() { + boolean shouldRecursive() { return nameHashCode == HASH_STAR || nameHashCode == HASH_EMPTY; } diff --git a/core/src/main/java/com/alibaba/fastjson2/JSONReader.java b/core/src/main/java/com/alibaba/fastjson2/JSONReader.java index 9a0a71887b..c075fce6d6 100644 --- a/core/src/main/java/com/alibaba/fastjson2/JSONReader.java +++ b/core/src/main/java/com/alibaba/fastjson2/JSONReader.java @@ -2163,7 +2163,7 @@ public void read(Map object, long features) { try { jsonPath = JSONPath.of(reference); } catch (Exception ignored) { - map.put(name, new JSONObject().fluentPut("$ref", reference)); + map.put(name, JSONObject.of("$ref", reference)); continue; } addResolveTask(map, name, jsonPath); diff --git a/core/src/main/java/com/alibaba/fastjson2/JSONReaderJSONB.java b/core/src/main/java/com/alibaba/fastjson2/JSONReaderJSONB.java index 57677df5ac..79598a93ea 100644 --- a/core/src/main/java/com/alibaba/fastjson2/JSONReaderJSONB.java +++ b/core/src/main/java/com/alibaba/fastjson2/JSONReaderJSONB.java @@ -81,27 +81,27 @@ final class JSONReaderJSONB FIXED_TYPE_SIZE = bytes; } - protected final byte[] bytes; - protected final int length; - protected final int end; + final byte[] bytes; + final int length; + final int end; - protected byte type; - protected int strlen; - protected byte strtype; - protected int strBegin; + byte type; + int strlen; + byte strtype; + int strBegin; - protected byte[] valueBytes; - protected char[] charBuf; - protected final CacheItem cacheItem; + byte[] valueBytes; + char[] charBuf; + final CacheItem cacheItem; - protected final SymbolTable symbolTable; + final SymbolTable symbolTable; - protected long symbol0Hash; - protected int symbol0Begin; - protected int symbol0Length; - protected byte symbol0StrType; + long symbol0Hash; + int symbol0Begin; + int symbol0Length; + byte symbol0StrType; - protected long[] symbols; + long[] symbols; JSONReaderJSONB(Context ctx, InputStream is) { super(ctx, true, false); @@ -2285,7 +2285,7 @@ public long readValueHashCode() { return hashCode; } - protected long getNameHashCode() { + long getNameHashCode() { int offset = strBegin; long nameValue = 0; for (int i = 0; i < strlen; offset++) { @@ -3774,7 +3774,7 @@ public Long readInt64() { return int64Value; } - protected String readFixedAsciiString(int strlen) { + String readFixedAsciiString(int strlen) { byte[] bytes = this.bytes; int offset = this.offset; String str; diff --git a/core/src/main/java/com/alibaba/fastjson2/JSONReaderUTF16.java b/core/src/main/java/com/alibaba/fastjson2/JSONReaderUTF16.java index 6cb2c7fdc4..a3f66687ef 100644 --- a/core/src/main/java/com/alibaba/fastjson2/JSONReaderUTF16.java +++ b/core/src/main/java/com/alibaba/fastjson2/JSONReaderUTF16.java @@ -2474,7 +2474,7 @@ public final int readInt32Value() { } if (comma = (ch == ',')) { - ch = offset == end ? EOI : (char) chars[offset++]; + ch = offset == end ? EOI : chars[offset++]; while (ch <= ' ' && ((1L << ch) & SPACE) != 0) { ch = offset == end ? EOI : chars[offset++]; } @@ -2571,7 +2571,7 @@ public final long readInt64Value() { } if (comma = (ch == ',')) { - ch = offset == end ? EOI : (char) chars[offset++]; + ch = offset == end ? EOI : chars[offset++]; while (ch <= ' ' && ((1L << ch) & SPACE) != 0) { ch = offset == end ? EOI : chars[offset++]; } @@ -5002,9 +5002,9 @@ public final boolean readBoolValue() { wasNull = true; offset += 3; val = false; - } else if (ch == '"') { + } else if (ch == '"' || ch == '\'') { if (offset + 1 < chars.length - && chars[offset + 1] == '"' + && chars[offset + 1] == ch ) { char c0 = chars[offset]; offset += 2; diff --git a/core/src/main/java/com/alibaba/fastjson2/JSONReaderUTF8.java b/core/src/main/java/com/alibaba/fastjson2/JSONReaderUTF8.java index 31c07815cf..a182b2642a 100644 --- a/core/src/main/java/com/alibaba/fastjson2/JSONReaderUTF8.java +++ b/core/src/main/java/com/alibaba/fastjson2/JSONReaderUTF8.java @@ -7152,9 +7152,9 @@ public final boolean readBoolValue() { wasNull = true; offset += 3; val = false; - } else if (ch == '"') { + } else if (ch == '"' || ch == '\'') { if (offset + 1 < bytes.length - && bytes[offset + 1] == '"' + && bytes[offset + 1] == ch ) { byte c0 = bytes[offset]; offset += 2; diff --git a/core/src/main/java/com/alibaba/fastjson2/JSONWriterUTF16JDK8UF.java b/core/src/main/java/com/alibaba/fastjson2/JSONWriterUTF16JDK8UF.java index 1a1c8bbecf..a8bd13e9c5 100644 --- a/core/src/main/java/com/alibaba/fastjson2/JSONWriterUTF16JDK8UF.java +++ b/core/src/main/java/com/alibaba/fastjson2/JSONWriterUTF16JDK8UF.java @@ -2,7 +2,6 @@ import com.alibaba.fastjson2.util.JDKUtils; -import static com.alibaba.fastjson2.JSONWriter.Feature.*; import static com.alibaba.fastjson2.util.JDKUtils.UNSAFE; public final class JSONWriterUTF16JDK8UF diff --git a/core/src/main/java/com/alibaba/fastjson2/codec/DateTimeCodec.java b/core/src/main/java/com/alibaba/fastjson2/codec/DateTimeCodec.java index 7c81b7647e..ef34af92e7 100644 --- a/core/src/main/java/com/alibaba/fastjson2/codec/DateTimeCodec.java +++ b/core/src/main/java/com/alibaba/fastjson2/codec/DateTimeCodec.java @@ -30,7 +30,7 @@ public DateTimeCodec(String format) { public DateTimeCodec(String format, Locale locale) { if (format != null) { - format = format.replaceAll("aa", "a"); + format = format.replace("aa", "a"); } this.format = format; diff --git a/core/src/main/java/com/alibaba/fastjson2/internal/asm/TypeCollector.java b/core/src/main/java/com/alibaba/fastjson2/internal/asm/TypeCollector.java index 7d8c3ea2b5..42389b2d68 100644 --- a/core/src/main/java/com/alibaba/fastjson2/internal/asm/TypeCollector.java +++ b/core/src/main/java/com/alibaba/fastjson2/internal/asm/TypeCollector.java @@ -9,7 +9,7 @@ public class TypeCollector { static final Map PRIMITIVES; static { - HashMap map = new HashMap(); + HashMap map = new HashMap<>(); map.put("int", "I"); map.put("boolean", "Z"); map.put("byte", "B"); @@ -75,21 +75,22 @@ protected MethodCollector visitMethod(int access, String name, String desc) { // } private boolean correctTypeName(Type type, String paramTypeName) { - String s = type.getClassName(); + String typeName = type.getClassName(); // array notation needs cleanup. StringBuilder braces = new StringBuilder(); - while (s.endsWith("[]")) { + while (typeName.endsWith("[]")) { braces.append('['); - s = s.substring(0, s.length() - 2); + typeName = typeName.substring(0, typeName.length() - 2); } if (braces.length() != 0) { - if (PRIMITIVES.containsKey(s)) { - s = braces.append(PRIMITIVES.get(s)).toString(); + String symbol = PRIMITIVES.get(typeName); + if (symbol != null) { + typeName = braces.append(symbol).toString(); } else { - s = braces.append('L').append(s).append(';').toString(); + typeName = braces.append('L').append(typeName).append(';').toString(); } } - return s.equals(paramTypeName); + return typeName.equals(paramTypeName); } public String[] getParameterNamesForMethod() { diff --git a/core/src/main/java/com/alibaba/fastjson2/reader/FieldReaderCollectionMethodReadOnly.java b/core/src/main/java/com/alibaba/fastjson2/reader/FieldReaderCollectionMethodReadOnly.java index 755a586974..ecd20cf3db 100644 --- a/core/src/main/java/com/alibaba/fastjson2/reader/FieldReaderCollectionMethodReadOnly.java +++ b/core/src/main/java/com/alibaba/fastjson2/reader/FieldReaderCollectionMethodReadOnly.java @@ -70,10 +70,6 @@ public void accept(T object, Object value) { return; } - if (value == collection) { - return; - } - Collection values = (Collection) value; for (Object item : values) { if (item == null) { diff --git a/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderBaseModule.java b/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderBaseModule.java index 639dc1e73d..1cbb54d7a3 100644 --- a/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderBaseModule.java +++ b/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderBaseModule.java @@ -1122,7 +1122,7 @@ private void processJSONField1x(FieldInfo fieldInfo, Annotation annotation) { format = format.trim(); if (format.indexOf('T') != -1 && !format.contains("'T'")) { - format = format.replaceAll("T", "'T'"); + format = format.replace("T", "'T'"); } fieldInfo.format = format; @@ -1227,7 +1227,7 @@ private void getFieldInfo(FieldInfo fieldInfo, JSONField jsonField) { if (!jsonFieldFormat.isEmpty()) { jsonFieldFormat = jsonFieldFormat.trim(); if (jsonFieldFormat.indexOf('T') != -1 && !jsonFieldFormat.contains("'T'")) { - jsonFieldFormat = jsonFieldFormat.replaceAll("T", "'T'"); + jsonFieldFormat = jsonFieldFormat.replace("T", "'T'"); } fieldInfo.format = jsonFieldFormat; @@ -1257,9 +1257,9 @@ private void getFieldInfo(FieldInfo fieldInfo, JSONField jsonField) { if (fieldInfo.alternateNames == null) { fieldInfo.alternateNames = alternateNames; } else { - Set nameSet = new LinkedHashSet<>(); - nameSet.addAll(Arrays.asList(alternateNames)); - nameSet.addAll(Arrays.asList(fieldInfo.alternateNames)); + Set nameSet = new LinkedHashSet<>(alternateNames.length + fieldInfo.alternateNames.length, 1F); + Collections.addAll(nameSet, alternateNames); + Collections.addAll(nameSet, fieldInfo.alternateNames); fieldInfo.alternateNames = nameSet.toArray(new String[nameSet.size()]); } } diff --git a/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderCreator.java b/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderCreator.java index 56db7085e4..24d9919a6d 100644 --- a/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderCreator.java +++ b/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderCreator.java @@ -724,27 +724,26 @@ protected ObjectReader createObjectReaderWithCreator( boolean[] flags = null; int maskCount = 0; - if (setterFieldReaders != null) { - for (int i = 0; i < setterFieldReaders.length; i++) { - FieldReader setterFieldReader = setterFieldReaders[i]; - if (fieldReaders.containsKey(setterFieldReader.fieldName)) { - if (flags == null) { - flags = new boolean[setterFieldReaders.length]; - } - flags[i] = true; - maskCount++; + // setterFieldReaders is NOT null here, otherwise Arrays.sort() will throw NPE + for (int i = 0; i < setterFieldReaders.length; i++) { + FieldReader setterFieldReader = setterFieldReaders[i]; + if (fieldReaders.containsKey(setterFieldReader.fieldName)) { + if (flags == null) { + flags = new boolean[setterFieldReaders.length]; } + flags[i] = true; + maskCount++; } - if (maskCount > 0) { - FieldReader[] array = new FieldReader[setterFieldReaders.length - maskCount]; - int index = 0; - for (int i = 0; i < setterFieldReaders.length; i++) { - if (!flags[i]) { - array[index++] = setterFieldReaders[i]; - } + } + if (maskCount > 0) { + FieldReader[] array = new FieldReader[setterFieldReaders.length - maskCount]; + int index = 0; + for (int i = 0; i < setterFieldReaders.length; i++) { + if (!flags[i]) { + array[index++] = setterFieldReaders[i]; } - setterFieldReaders = array; } + setterFieldReaders = array; } return (ObjectReader) new ObjectReaderNoneDefaultConstructor( diff --git a/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderNoneDefaultConstructor.java b/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderNoneDefaultConstructor.java index a6364be2d8..b274f942b0 100644 --- a/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderNoneDefaultConstructor.java +++ b/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderNoneDefaultConstructor.java @@ -336,10 +336,7 @@ public T readObject(JSONReader jsonReader, Type fieldType, Object fieldName, lon } for (FieldReader fieldReader : fieldReaders) { if (fieldReader.defaultValue != null) { - Object fieldValue = valueMap.get(fieldReader.fieldNameHash); - if (fieldValue == null) { - valueMap.put(fieldReader.fieldNameHash, fieldReader.defaultValue); - } + valueMap.putIfAbsent(fieldReader.fieldNameHash, fieldReader.defaultValue); } } } diff --git a/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderRootName.java b/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderRootName.java index 4823c16669..368bed014e 100644 --- a/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderRootName.java +++ b/core/src/main/java/com/alibaba/fastjson2/reader/ObjectReaderRootName.java @@ -12,8 +12,8 @@ public final class ObjectReaderRootName extends ObjectReaderAdapter { - protected final String rootName; - protected final long rootNameHashCode; + final String rootName; + final long rootNameHashCode; public ObjectReaderRootName( Class objectClass, diff --git a/core/src/main/java/com/alibaba/fastjson2/schema/ArraySchema.java b/core/src/main/java/com/alibaba/fastjson2/schema/ArraySchema.java index 211f76171d..da18a1cda8 100644 --- a/core/src/main/java/com/alibaba/fastjson2/schema/ArraySchema.java +++ b/core/src/main/java/com/alibaba/fastjson2/schema/ArraySchema.java @@ -329,18 +329,7 @@ public JSONObject toJSONObject() { object.put("uniqueItems", uniqueItems); } - if (allOf != null) { - object.put("allOf", allOf); - } - - if (anyOf != null) { - object.put("anyOf", anyOf); - } - - if (oneOf != null) { - object.put("oneOf", oneOf); - } - return object; + return injectIfPresent(object, allOf, anyOf, oneOf); } @Override diff --git a/core/src/main/java/com/alibaba/fastjson2/schema/JSONSchema.java b/core/src/main/java/com/alibaba/fastjson2/schema/JSONSchema.java index 77204dd3da..1374fe6392 100644 --- a/core/src/main/java/com/alibaba/fastjson2/schema/JSONSchema.java +++ b/core/src/main/java/com/alibaba/fastjson2/schema/JSONSchema.java @@ -641,18 +641,10 @@ public static JSONSchema of(JSONObject input, JSONSchema parent) { static AnyOf anyOf(JSONObject input, Class type) { JSONArray array = input.getJSONArray("anyOf"); - if (array == null || array.isEmpty()) { - return null; - } - JSONSchema[] items = new JSONSchema[array.size()]; - for (int i = 0; i < items.length; i++) { - items[i] = JSONSchema.of(array.getJSONObject(i), type); - } - - return new AnyOf(items); + return anyOf(array, type); } - static AnyOf anyOf(JSONArray array, Class type) { + static JSONSchema[] makeSchemaItems(JSONArray array, Class type) { if (array == null || array.isEmpty()) { return null; } @@ -660,46 +652,28 @@ static AnyOf anyOf(JSONArray array, Class type) { for (int i = 0; i < items.length; i++) { items[i] = JSONSchema.of(array.getJSONObject(i), type); } + return items; + } - return new AnyOf(items); + static AnyOf anyOf(JSONArray array, Class type) { + JSONSchema[] items = makeSchemaItems(array, type); + return items == null ? null : new AnyOf(items); } static AllOf allOf(JSONObject input, Class type) { JSONArray array = input.getJSONArray("allOf"); - if (array == null || array.isEmpty()) { - return null; - } - - JSONSchema[] items = new JSONSchema[array.size()]; - for (int i = 0; i < items.length; i++) { - items[i] = JSONSchema.of(array.getJSONObject(i), type); - } - return new AllOf(items); + JSONSchema[] items = makeSchemaItems(array, type); + return items == null ? null : new AllOf(items); } static OneOf oneOf(JSONObject input, Class type) { JSONArray array = input.getJSONArray("oneOf"); - if (array == null || array.isEmpty()) { - return null; - } - - JSONSchema[] items = new JSONSchema[array.size()]; - for (int i = 0; i < items.length; i++) { - items[i] = JSONSchema.of(array.getJSONObject(i), type); - } - return new OneOf(items); + return oneOf(array, type); } static OneOf oneOf(JSONArray array, Class type) { - if (array == null || array.isEmpty()) { - return null; - } - - JSONSchema[] items = new JSONSchema[array.size()]; - for (int i = 0; i < items.length; i++) { - items[i] = JSONSchema.of(array.getJSONObject(i), type); - } - return new OneOf(items); + JSONSchema[] items = makeSchemaItems(array, type); + return items == null ? null : new OneOf(items); } public String getTitle() { @@ -943,4 +917,19 @@ public void write(JSONWriter jsonWriter, public void accept(Predicate v) { v.test(this); } + + static JSONObject injectIfPresent(JSONObject object, AllOf allOf, AnyOf anyOf, OneOf oneOf) { + if (allOf != null) { + object.put("allOf", allOf); + } + + if (anyOf != null) { + object.put("anyOf", anyOf); + } + + if (oneOf != null) { + object.put("oneOf", oneOf); + } + return object; + } } diff --git a/core/src/main/java/com/alibaba/fastjson2/schema/ObjectSchema.java b/core/src/main/java/com/alibaba/fastjson2/schema/ObjectSchema.java index 43c8478d73..76dde54636 100644 --- a/core/src/main/java/com/alibaba/fastjson2/schema/ObjectSchema.java +++ b/core/src/main/java/com/alibaba/fastjson2/schema/ObjectSchema.java @@ -673,19 +673,7 @@ public JSONObject toJSONObject() { object.put("else", elseSchema); } - if (allOf != null) { - object.put("allOf", allOf); - } - - if (anyOf != null) { - object.put("anyOf", anyOf); - } - - if (oneOf != null) { - object.put("oneOf", oneOf); - } - - return object; + return injectIfPresent(object, allOf, anyOf, oneOf); } public void accept(Predicate v) { diff --git a/core/src/main/java/com/alibaba/fastjson2/schema/StringSchema.java b/core/src/main/java/com/alibaba/fastjson2/schema/StringSchema.java index f9baa630f6..ad548f5ad9 100644 --- a/core/src/main/java/com/alibaba/fastjson2/schema/StringSchema.java +++ b/core/src/main/java/com/alibaba/fastjson2/schema/StringSchema.java @@ -64,7 +64,7 @@ public final class StringSchema Object property = input.get("enum"); if (property instanceof Collection) { Collection enums = (Collection) property; - enumValues = new LinkedHashSet<>(enums.size()); + enumValues = new LinkedHashSet<>(enums.size(), 1F); enumValues.addAll((Collection) enums); } else if (property instanceof Object[]) { enumValues = input.getObject("enum", TypeReference.collectionType(LinkedHashSet.class, String.class)); diff --git a/core/src/main/java/com/alibaba/fastjson2/util/DateUtils.java b/core/src/main/java/com/alibaba/fastjson2/util/DateUtils.java index dd268ed9f3..a8057fc378 100644 --- a/core/src/main/java/com/alibaba/fastjson2/util/DateUtils.java +++ b/core/src/main/java/com/alibaba/fastjson2/util/DateUtils.java @@ -1053,7 +1053,7 @@ public static LocalDate parseLocalDate8(char[] str, int off) { } else if (c1 == '-' && str[off + 5] == '-') { // d-MMM-yy dom = digit1(str, off); - month = DateUtils.month((char) str[off + 2], c3, c4); + month = DateUtils.month(str[off + 2], c3, c4); year = digit2(str, off + 6); if (year != -1) { year += 2000; @@ -1325,7 +1325,7 @@ public static LocalDate parseLocalDate10(char[] str, int off) { } else if (c1 == ' ' && c5 == ' ') { // d MMM yyyy dom = digit1(str, off); - month = DateUtils.month(c2, (char) str[off + 3], c4); + month = DateUtils.month(c2, str[off + 3], c4); year = digit4(str, off + 6); } else { return null; @@ -1677,7 +1677,7 @@ public static LocalDateTime parseLocalDateTime17(char[] str, int off) { char c15 = str[off + 15]; char c16 = str[off + 16]; - int year, month, dom, hour, minute, second = 0, nanoOfSecond = 0; + int year, month, dom, hour, minute, second, nanoOfSecond = 0; if (c4 == '-' && c7 == '-' && (c10 == 'T' || c10 == ' ') && c13 == ':' && c16 == 'Z') { year = digit4(str, off); month = digit2(str, off + 5); @@ -5657,23 +5657,7 @@ public static long parseMillisYMDHMS19(String str, ZoneId zoneId) { long utcSeconds; { - final int DAYS_PER_CYCLE = 146097; - final long DAYS_0000_TO_1970 = (DAYS_PER_CYCLE * 5L) - (30L * 365L + 7L); - - long total = (365 * year) - + ((year + 3) / 4 - (year + 99) / 100 + (year + 399) / 400) - + ((367 * month - 362) / 12) - + (dom - 1); - - if (month > 2) { - total--; - boolean leapYear = (year & 3) == 0 && ((year % 100) != 0 || (year % 400) == 0); - if (!leapYear) { - total--; - } - } - - long epochDay = total - DAYS_0000_TO_1970; + long epochDay = calcEpochDay(year, month, dom); utcSeconds = epochDay * 86400 + hour * 3600 + minute * 60 @@ -5702,6 +5686,26 @@ public static long parseMillisYMDHMS19(String str, ZoneId zoneId) { return (utcSeconds - zoneOffsetTotalSeconds) * 1000L; } + private static long calcEpochDay(int year, int month, int dom) { + final int DAYS_PER_CYCLE = 146097; + final long DAYS_0000_TO_1970 = (DAYS_PER_CYCLE * 5L) - (30L * 365L + 7L); + + long total = (365 * year) + + ((year + 3) / 4 - (year + 99) / 100 + (year + 399) / 400) + + ((367 * month - 362) / 12) + + (dom - 1); + + if (month > 2) { + total--; + boolean leapYear = (year & 3) == 0 && ((year % 100) != 0 || (year % 400) == 0); + if (!leapYear) { + total--; + } + } + + return total - DAYS_0000_TO_1970; + } + static long parseMillis19( String str, ZoneId zoneId, @@ -5979,23 +5983,7 @@ static long parseMillis19( long utcSeconds; { - final int DAYS_PER_CYCLE = 146097; - final long DAYS_0000_TO_1970 = (DAYS_PER_CYCLE * 5L) - (30L * 365L + 7L); - - long total = (365 * year) - + ((year + 3) / 4 - (year + 99) / 100 + (year + 399) / 400) - + ((367 * month - 362) / 12) - + (dom - 1); - - if (month > 2) { - total--; - boolean leapYear = (year & 3) == 0 && ((year % 100) != 0 || (year % 400) == 0); - if (!leapYear) { - total--; - } - } - - long epochDay = total - DAYS_0000_TO_1970; + long epochDay = calcEpochDay(year, month, dom); utcSeconds = epochDay * 86400 + hour * 3600 + minute * 60 @@ -6181,23 +6169,7 @@ static long parseMillis10( long utcSeconds; { - final int DAYS_PER_CYCLE = 146097; - final long DAYS_0000_TO_1970 = (DAYS_PER_CYCLE * 5L) - (30L * 365L + 7L); - - long total = (365 * year) - + ((year + 3) / 4 - (year + 99) / 100 + (year + 399) / 400) - + ((367 * month - 362) / 12) - + (dom - 1); - - if (month > 2) { - total--; - boolean leapYear = (year & 3) == 0 && ((year % 100) != 0 || (year % 400) == 0); - if (!leapYear) { - total--; - } - } - - long epochDay = total - DAYS_0000_TO_1970; + long epochDay = calcEpochDay(year, month, dom); utcSeconds = epochDay * 86400; } @@ -6586,23 +6558,7 @@ public static long parseMillis19(String str, ZoneId zoneId) { long utcSeconds; { - final int DAYS_PER_CYCLE = 146097; - final long DAYS_0000_TO_1970 = (DAYS_PER_CYCLE * 5L) - (30L * 365L + 7L); - - long total = (365 * year) - + ((year + 3) / 4 - (year + 99) / 100 + (year + 399) / 400) - + ((367 * month - 362) / 12) - + (dom - 1); - - if (month > 2) { - total--; - boolean leapYear = (year & 3) == 0 && ((year % 100) != 0 || (year % 400) == 0); - if (!leapYear) { - total--; - } - } - - long epochDay = total - DAYS_0000_TO_1970; + long epochDay = calcEpochDay(year, month, dom); utcSeconds = epochDay * 86400 + hour * 3600 + minute * 60 @@ -6937,23 +6893,7 @@ public static long parseMillis19(byte[] bytes, int off, ZoneId zoneId) { long utcSeconds; { - final int DAYS_PER_CYCLE = 146097; - final long DAYS_0000_TO_1970 = (DAYS_PER_CYCLE * 5L) - (30L * 365L + 7L); - - long total = (365 * year) - + ((year + 3) / 4 - (year + 99) / 100 + (year + 399) / 400) - + ((367 * month - 362) / 12) - + (dom - 1); - - if (month > 2) { - total--; - boolean leapYear = (year & 3) == 0 && ((year % 100) != 0 || (year % 400) == 0); - if (!leapYear) { - total--; - } - } - - long epochDay = total - DAYS_0000_TO_1970; + long epochDay = calcEpochDay(year, month, dom); utcSeconds = epochDay * 86400 + hour * 3600 + minute * 60 @@ -7289,23 +7229,7 @@ public static long parseMillis19(char[] bytes, int off, ZoneId zoneId) { long utcSeconds; { - final int DAYS_PER_CYCLE = 146097; - final long DAYS_0000_TO_1970 = (DAYS_PER_CYCLE * 5L) - (30L * 365L + 7L); - - long total = (365 * year) - + ((year + 3) / 4 - (year + 99) / 100 + (year + 399) / 400) - + ((367 * month - 362) / 12) - + (dom - 1); - - if (month > 2) { - total--; - boolean leapYear = (year & 3) == 0 && ((year % 100) != 0 || (year % 400) == 0); - if (!leapYear) { - total--; - } - } - - long epochDay = total - DAYS_0000_TO_1970; + long epochDay = calcEpochDay(year, month, dom); utcSeconds = epochDay * 86400 + hour * 3600 + minute * 60 @@ -7566,23 +7490,7 @@ public static long millis( long utcSeconds; { - final int DAYS_PER_CYCLE = 146097; - final long DAYS_0000_TO_1970 = (DAYS_PER_CYCLE * 5L) - (30L * 365L + 7L); - - long total = (365 * year) - + ((year + 3) / 4 - (year + 99) / 100 + (year + 399) / 400) - + ((367 * month - 362) / 12) - + (dom - 1); - - if (month > 2) { - total--; - boolean leapYear = (year & 3) == 0 && ((year % 100) != 0 || (year % 400) == 0); - if (!leapYear) { - total--; - } - } - - long epochDay = total - DAYS_0000_TO_1970; + long epochDay = calcEpochDay(year, month, dom); utcSeconds = epochDay * 86400 + hour * 3600 + minute * 60 @@ -7620,23 +7528,7 @@ public static long utcSeconds( int minute, int second ) { - final int DAYS_PER_CYCLE = 146097; - final long DAYS_0000_TO_1970 = (DAYS_PER_CYCLE * 5L) - (30L * 365L + 7L); - - long total = (365 * year) - + ((year + 3) / 4 - (year + 99) / 100 + (year + 399) / 400) - + ((367 * month - 362) / 12) - + (dom - 1); - - if (month > 2) { - total--; - boolean leapYear = (year & 3) == 0 && ((year % 100) != 0 || (year % 400) == 0); - if (!leapYear) { - total--; - } - } - - long epochDay = total - DAYS_0000_TO_1970; + long epochDay = calcEpochDay(year, month, dom); return epochDay * 86400 + hour * 3600 + minute * 60 diff --git a/core/src/main/java/com/alibaba/fastjson2/util/FDBigInteger.java b/core/src/main/java/com/alibaba/fastjson2/util/FDBigInteger.java index e90ed00ad7..71bcfb2b6e 100644 --- a/core/src/main/java/com/alibaba/fastjson2/util/FDBigInteger.java +++ b/core/src/main/java/com/alibaba/fastjson2/util/FDBigInteger.java @@ -164,7 +164,7 @@ private FDBigInteger mult(FDBigInteger other) { } private static void mult(int[] src, int srcLen, int value, int[] dst) { - long val = value & 0XFFFFFFFFL; + final long val = value & 0XFFFFFFFFL; long carry = 0; for (int i = 0; i < srcLen; i++) { long product = (src[i] & 0XFFFFFFFFL) * val + carry; @@ -188,16 +188,9 @@ private static void mult(int[] s1, int s1Len, int[] s2, int s2Len, int[] dst) { } private static void mult(int[] src, int srcLen, int v0, int v1, int[] dst) { - long v = v0 & 0XFFFFFFFFL; + mult(src, srcLen, v0, dst); + long v = v1 & 0XFFFFFFFFL; long carry = 0; - for (int j = 0; j < srcLen; j++) { - long product = v * (src[j] & 0XFFFFFFFFL) + carry; - dst[j] = (int) product; - carry = product >>> 32; - } - dst[srcLen] = (int) carry; - v = v1 & 0XFFFFFFFFL; - carry = 0; for (int j = 0; j < srcLen; j++) { long product = (dst[j + 1] & 0XFFFFFFFFL) + v * (src[j] & 0XFFFFFFFFL) + carry; dst[j + 1] = (int) product; diff --git a/core/src/main/java/com/alibaba/fastjson2/util/IOUtils.java b/core/src/main/java/com/alibaba/fastjson2/util/IOUtils.java index 8d353ac57f..9fcab7d077 100644 --- a/core/src/main/java/com/alibaba/fastjson2/util/IOUtils.java +++ b/core/src/main/java/com/alibaba/fastjson2/util/IOUtils.java @@ -1037,10 +1037,8 @@ public static int writeInt64(char[] buf, int pos, final long value) { long i; if (value < 0) { if (value == Long.MIN_VALUE) { - if (value == Long.MIN_VALUE) { - System.arraycopy(MIN_LONG_CHARS, 0, buf, pos, MIN_LONG_CHARS.length); - return pos + MIN_LONG_CHARS.length; - } + System.arraycopy(MIN_LONG_CHARS, 0, buf, pos, MIN_LONG_CHARS.length); + return pos + MIN_LONG_CHARS.length; } i = -value; putChar(buf, pos++, '-'); diff --git a/core/src/main/java/com/alibaba/fastjson2/util/TypeUtils.java b/core/src/main/java/com/alibaba/fastjson2/util/TypeUtils.java index e83f4033e9..fbf58e781c 100644 --- a/core/src/main/java/com/alibaba/fastjson2/util/TypeUtils.java +++ b/core/src/main/java/com/alibaba/fastjson2/util/TypeUtils.java @@ -1001,7 +1001,7 @@ public static double doubleValue(boolean isNegative, int decExp, char[] digits, if (ieeeBits == 0 || ieeeBits == DOUBLE_EXP_BIT_MASK) { // 0.0 or Double.POSITIVE_INFINITY break; // oops. Fell off end of range. } - continue; // try again. + // try again. } } if (isNegative) { @@ -1404,9 +1404,10 @@ public static T cast(Object obj, Type type) { return cast(obj, type, JSONFactory.getDefaultObjectReaderProvider()); } + @SuppressWarnings({ "rawtypes", "unchecked" }) public static T cast(Object obj, Type type, ObjectReaderProvider provider) { if (type instanceof Class) { - return (T) cast(obj, (Class) type, provider); + return cast(obj, (Class) type, provider); } if (obj instanceof Collection) { @@ -1429,6 +1430,7 @@ public static T cast(Object obj, Class targetClass) { return cast(obj, targetClass, JSONFactory.getDefaultObjectReaderProvider()); } + @SuppressWarnings({ "rawtypes", "unchecked" }) public static T cast(Object obj, Class targetClass, ObjectReaderProvider provider) { if (obj == null) { return null; diff --git a/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterBaseModule.java b/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterBaseModule.java index 899fcacd85..55b45fbbe7 100644 --- a/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterBaseModule.java +++ b/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterBaseModule.java @@ -980,7 +980,7 @@ private void loadJsonFieldFormat(FieldInfo fieldInfo, String jsonFieldFormat) { jsonFieldFormat = jsonFieldFormat.trim(); if (jsonFieldFormat.indexOf('T') != -1 && !jsonFieldFormat.contains("'T'")) { - jsonFieldFormat = jsonFieldFormat.replaceAll("T", "'T'"); + jsonFieldFormat = jsonFieldFormat.replace("T", "'T'"); } if (!jsonFieldFormat.isEmpty()) { diff --git a/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterCreator.java b/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterCreator.java index d2425f2093..b6c5ffadec 100644 --- a/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterCreator.java +++ b/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterCreator.java @@ -492,7 +492,7 @@ boolean record = BeanUtils.isRecord(objectClass); } else if (firstChar >= 'a' && firstChar <= 'z') { sameFieldName = (char) (firstChar - 32) + fieldName.substring(1); } - if (sameFieldName != null && fieldWriterMap.containsKey(sameFieldName)) { + if (sameFieldName != null) { fieldWriterMap.remove(sameFieldName); } } @@ -519,7 +519,7 @@ boolean record = BeanUtils.isRecord(objectClass); SUPER, superType, objectClass.getSuperclass(), - o -> o + Function.identity() ); fieldWriters.add(superWriter); } diff --git a/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterCreatorASM.java b/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterCreatorASM.java index 92d22a4d18..b7f32d3347 100644 --- a/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterCreatorASM.java +++ b/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterCreatorASM.java @@ -355,7 +355,7 @@ boolean record = BeanUtils.isRecord(objectClass); } else if (firstChar >= 'a' && firstChar <= 'z') { sameFieldName = (char) (firstChar - 32) + fieldName.substring(1); } - if (sameFieldName != null && fieldWriterMap.containsKey(sameFieldName)) { + if (sameFieldName != null) { fieldWriterMap.remove(sameFieldName); } } diff --git a/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterImplDouble.java b/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterImplDouble.java index d4430b1f1f..03c6543afb 100644 --- a/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterImplDouble.java +++ b/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterImplDouble.java @@ -40,7 +40,7 @@ public void write(JSONWriter jsonWriter, Object object, Object fieldName, Type f DecimalFormat decimalFormat = this.format; if (decimalFormat == null) { String format = jsonWriter.getContext().getDateFormat(); - if (format != null && format.indexOf("#") != -1) { + if (format != null && format.indexOf('#') != -1) { decimalFormat = new DecimalFormat(format); } } diff --git a/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterProvider.java b/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterProvider.java index 6e8b783ca7..143b28b88b 100644 --- a/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterProvider.java +++ b/core/src/main/java/com/alibaba/fastjson2/writer/ObjectWriterProvider.java @@ -394,14 +394,11 @@ private ObjectWriter getObjectWriterInternal(Type objectType, Class objectClass, if (fieldBased) { fieldBased = false; objectWriter = cacheFieldBased.get(objectType); - if (objectWriter != null) { - return objectWriter; - } } else { objectWriter = cache.get(objectType); - if (objectWriter != null) { - return objectWriter; - } + } + if (objectWriter != null) { + return objectWriter; } } diff --git a/core/src/test/java/com/alibaba/fastjson2/issues_3200/Issue3283.java b/core/src/test/java/com/alibaba/fastjson2/issues_3200/Issue3283.java new file mode 100644 index 0000000000..fbcd107eb9 --- /dev/null +++ b/core/src/test/java/com/alibaba/fastjson2/issues_3200/Issue3283.java @@ -0,0 +1,38 @@ +package com.alibaba.fastjson2.issues_3200; + +import com.alibaba.fastjson2.JSONObject; +import org.junit.Test; +import org.junit.jupiter.api.Assertions; + +public class Issue3283 { + static class Bean { + private boolean test; + + public boolean isTest() { + return test; + } + + public void setTest(boolean test) { + this.test = test; + } + } + + @Test + public void singleQuote() { + String text = "{'test': 'true'}"; + Bean bean = JSONObject.parseObject(text, Bean.class); + Assertions.assertTrue(bean.isTest()); + + text = "{'test': ''}"; + bean = JSONObject.parseObject(text, Bean.class); + Assertions.assertFalse(bean.isTest()); + + text = "{'test': 'Y'}"; + bean = JSONObject.parseObject(text, Bean.class); + Assertions.assertTrue(bean.isTest()); + + text = "{'test': '1'}"; + bean = JSONObject.parseObject(text, Bean.class); + Assertions.assertTrue(bean.isTest()); + } +} diff --git a/core/src/test/java/com/alibaba/fastjson2/primitves/UUIDTest.java b/core/src/test/java/com/alibaba/fastjson2/primitves/UUIDTest.java index ce223095e3..9c7179d9b5 100644 --- a/core/src/test/java/com/alibaba/fastjson2/primitves/UUIDTest.java +++ b/core/src/test/java/com/alibaba/fastjson2/primitves/UUIDTest.java @@ -82,7 +82,7 @@ public void readUUID() { uuid, JSONReader.ofJSONB( JSONB.toBytes( - str.replaceAll("-", "") + str.replace("-", "") ) ).readUUID() ); diff --git a/core/src/test/java/com/alibaba/fastjson2/primitves/UUIDTest3.java b/core/src/test/java/com/alibaba/fastjson2/primitves/UUIDTest3.java index dc55e3c702..8ffa442827 100644 --- a/core/src/test/java/com/alibaba/fastjson2/primitves/UUIDTest3.java +++ b/core/src/test/java/com/alibaba/fastjson2/primitves/UUIDTest3.java @@ -17,7 +17,7 @@ public class UUIDTest3 { }; static String toString(UUID id) { - return id.toString().replaceAll("-", ""); + return id.toString().replace("-", ""); } @Test diff --git a/core/src/test/java/com/alibaba/fastjson2_demo/Int2Decoder.java b/core/src/test/java/com/alibaba/fastjson2_demo/Int2Decoder.java index e0627d4c79..bc9910d886 100644 --- a/core/src/test/java/com/alibaba/fastjson2_demo/Int2Decoder.java +++ b/core/src/test/java/com/alibaba/fastjson2_demo/Int2Decoder.java @@ -12,9 +12,9 @@ public void acceptField(JSONReader jsonReader, Int2 object, long hashCode) { if (hashCode == V0) { int fieldInt = jsonReader.readInt32Value(); object.setV0000(fieldInt); - } else if (hashCode == V0) { + } else if (hashCode == V1) { int fieldInt = jsonReader.readInt32Value(); - object.setV0000(fieldInt); + object.setV0001(fieldInt); } } } diff --git a/example-spring-test/src/main/java/com/alibaba/fastjson2/example/springtest/controller/TestController.java b/example-spring-test/src/main/java/com/alibaba/fastjson2/example/springtest/controller/TestController.java index 454d84af1d..bd1c8f6b4a 100644 --- a/example-spring-test/src/main/java/com/alibaba/fastjson2/example/springtest/controller/TestController.java +++ b/example-spring-test/src/main/java/com/alibaba/fastjson2/example/springtest/controller/TestController.java @@ -24,8 +24,7 @@ public User test(User user) { @GetMapping(value = "/hello", produces = "text/html") public void hello(HttpServletResponse response) { //返回一个html测试页面 - try (ServletOutputStream servletOutputStream = response.getOutputStream(); - ) { + try (ServletOutputStream servletOutputStream = response.getOutputStream()) { ClassPathResource classPathResource = new ClassPathResource("hello.html"); servletOutputStream.write(classPathResource.readBytes()); } catch (IOException e) { diff --git a/extension-jaxrs/extension-jaxrs-javax/src/main/java/com/alibaba/fastjson2/support/jaxrs/javax/FastJson2Provider.java b/extension-jaxrs/extension-jaxrs-javax/src/main/java/com/alibaba/fastjson2/support/jaxrs/javax/FastJson2Provider.java index 8ca7fba943..e3d6b46fc5 100644 --- a/extension-jaxrs/extension-jaxrs-javax/src/main/java/com/alibaba/fastjson2/support/jaxrs/javax/FastJson2Provider.java +++ b/extension-jaxrs/extension-jaxrs-javax/src/main/java/com/alibaba/fastjson2/support/jaxrs/javax/FastJson2Provider.java @@ -73,7 +73,7 @@ public class FastJson2Provider * Can serialize/deserialize all types. */ public FastJson2Provider() { - this((Class[]) null); + this(null); } /** diff --git a/extension-solon/src/main/java/com/alibaba/fastjson2/support/solon/Fastjson2ActionExecutor.java b/extension-solon/src/main/java/com/alibaba/fastjson2/support/solon/Fastjson2ActionExecutor.java index 1ce8e7463e..b31ddce36d 100644 --- a/extension-solon/src/main/java/com/alibaba/fastjson2/support/solon/Fastjson2ActionExecutor.java +++ b/extension-solon/src/main/java/com/alibaba/fastjson2/support/solon/Fastjson2ActionExecutor.java @@ -81,7 +81,7 @@ protected Object changeValue(Context ctx, ParamWrap p, int pi, Class pt, Obje return super.changeValue(ctx, p, pi, pt, bodyObj); } - if (p.spec().isRequiredBody() == false && ctx.paramMap().containsKey(p.spec().getName())) { + if (!p.spec().isRequiredBody() && ctx.paramMap().containsKey(p.spec().getName())) { //If path、queryString? return super.changeValue(ctx, p, pi, pt, bodyObj); } @@ -93,7 +93,7 @@ protected Object changeValue(Context ctx, ParamWrap p, int pi, Class pt, Obje if (bodyObj instanceof JSONObject) { JSONObject tmp = (JSONObject) bodyObj; - if (p.spec().isRequiredBody() == false) { + if (!p.spec().isRequiredBody()) { // //If there is no body requirement; Try to find by attribute // diff --git a/extension-spring5/src/main/java/com/alibaba/fastjson2/support/spring/data/mongodb/GeoJsonPointReader.java b/extension-spring5/src/main/java/com/alibaba/fastjson2/support/spring/data/mongodb/GeoJsonPointReader.java index 1e8a4db35a..3efa0d34d8 100644 --- a/extension-spring5/src/main/java/com/alibaba/fastjson2/support/spring/data/mongodb/GeoJsonPointReader.java +++ b/extension-spring5/src/main/java/com/alibaba/fastjson2/support/spring/data/mongodb/GeoJsonPointReader.java @@ -28,11 +28,7 @@ public GeoJsonPoint readObject(JSONReader jsonReader, Type fieldType, Object fie jsonReader.nextIfObjectStart(); double x = 0, y = 0; - for (; ; ) { - if (jsonReader.nextIfObjectEnd()) { - break; - } - + while (!jsonReader.nextIfObjectEnd()) { long nameHashCode = jsonReader.readFieldNameHashCode(); if (nameHashCode == HASH_TYPE) { long valueHashCode = jsonReader.readValueHashCode(); diff --git a/extension-spring5/src/main/java/com/alibaba/fastjson2/support/spring/data/mongodb/GeoJsonPolygonReader.java b/extension-spring5/src/main/java/com/alibaba/fastjson2/support/spring/data/mongodb/GeoJsonPolygonReader.java index cf2932c07b..37bebeccb5 100644 --- a/extension-spring5/src/main/java/com/alibaba/fastjson2/support/spring/data/mongodb/GeoJsonPolygonReader.java +++ b/extension-spring5/src/main/java/com/alibaba/fastjson2/support/spring/data/mongodb/GeoJsonPolygonReader.java @@ -33,11 +33,7 @@ public GeoJsonPolygon readObject(JSONReader jsonReader, Type fieldType, Object f List points = new ArrayList<>(); - for (; ; ) { - if (jsonReader.nextIfObjectEnd()) { - break; - } - + while (!jsonReader.nextIfObjectEnd()) { long nameHashCode = jsonReader.readFieldNameHashCode(); if (nameHashCode == HASH_TYPE) { long valueHashCode = jsonReader.readValueHashCode(); diff --git a/extension-spring5/src/main/java/com/alibaba/fastjson2/support/spring/http/codec/Fastjson2Encoder.java b/extension-spring5/src/main/java/com/alibaba/fastjson2/support/spring/http/codec/Fastjson2Encoder.java index 836907d2ce..70b47dc821 100644 --- a/extension-spring5/src/main/java/com/alibaba/fastjson2/support/spring/http/codec/Fastjson2Encoder.java +++ b/extension-spring5/src/main/java/com/alibaba/fastjson2/support/spring/http/codec/Fastjson2Encoder.java @@ -81,7 +81,7 @@ public DataBuffer encodeValue(@Nullable Object value, } private void configFilter(JSONWriter.Context context, Filter... filters) { - if (filters == null || filters.length == 0) { + if (filters == null) { return; } for (Filter filter : filters) { diff --git a/extension-spring5/src/main/java/com/alibaba/fastjson2/support/spring/webservlet/view/FastJsonJsonView.java b/extension-spring5/src/main/java/com/alibaba/fastjson2/support/spring/webservlet/view/FastJsonJsonView.java index 6d7d350af9..90fa4a3900 100644 --- a/extension-spring5/src/main/java/com/alibaba/fastjson2/support/spring/webservlet/view/FastJsonJsonView.java +++ b/extension-spring5/src/main/java/com/alibaba/fastjson2/support/spring/webservlet/view/FastJsonJsonView.java @@ -11,9 +11,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; +import java.util.*; /** * Fastjson for Spring MVC View. @@ -151,29 +149,34 @@ public void setUpdateContentLength(boolean updateContentLength) { * @return the object to be rendered */ protected Object filterModel(Map model) { - Map result = new HashMap(model.size()); - Set renderedAttributes = !CollectionUtils.isEmpty(this.renderedAttributes) ? // - this.renderedAttributes // - : model.keySet(); + int expectSize = model.size(); + final Set renderedKeys; + if (CollectionUtils.isEmpty(this.renderedAttributes)) { + renderedKeys = null; + } else { + renderedKeys = this.renderedAttributes; + expectSize = renderedKeys.size(); + } + // This is a high frequency operation and is worth optimizing separately. + if (expectSize == 1 && extractValueFromSingleKeyModel) { + Object value = renderedKeys != null + ? model.get(renderedKeys.iterator().next()) + : model.values().iterator().next(); + return value instanceof BindingResult ? Collections.emptyMap() : value; + } + final Map result = new HashMap<>(expectSize, 1F); for (Map.Entry entry : model.entrySet()) { if (!(entry.getValue() instanceof BindingResult) - && renderedAttributes.contains(entry.getKey())) { + && (renderedKeys == null || renderedKeys.contains(entry.getKey()))) { result.put(entry.getKey(), entry.getValue()); } } - if (extractValueFromSingleKeyModel) { - if (result.size() == 1) { - for (Map.Entry entry : result.entrySet()) { - return entry.getValue(); - } + if (extractValueFromSingleKeyModel && result.size() == 1) { + for (Map.Entry entry : result.entrySet()) { + return entry.getValue(); } } return result; } - - @Override - protected void setResponseContentType(HttpServletRequest request, HttpServletResponse response) { - super.setResponseContentType(request, response); - } } diff --git a/extension/src/main/java/com/alibaba/fastjson2/support/AwtRederModule.java b/extension/src/main/java/com/alibaba/fastjson2/support/AwtRederModule.java index 03784ca54e..543591a09d 100644 --- a/extension/src/main/java/com/alibaba/fastjson2/support/AwtRederModule.java +++ b/extension/src/main/java/com/alibaba/fastjson2/support/AwtRederModule.java @@ -72,7 +72,7 @@ static class ColorCreator public Color apply(Map values) { Integer rgb = (Integer) values.get(HASH_RGB); if (rgb != null) { - return new Color(rgb.intValue()); + return new Color(rgb); } Integer r = (Integer) values.get(HASH_R); diff --git a/extension/src/main/java/com/alibaba/fastjson2/support/arrow/ArrowByteArrayConsumer.java b/extension/src/main/java/com/alibaba/fastjson2/support/arrow/ArrowByteArrayConsumer.java index 29d937b8ec..def961e299 100644 --- a/extension/src/main/java/com/alibaba/fastjson2/support/arrow/ArrowByteArrayConsumer.java +++ b/extension/src/main/java/com/alibaba/fastjson2/support/arrow/ArrowByteArrayConsumer.java @@ -11,6 +11,7 @@ import org.apache.arrow.vector.types.pojo.Schema; import java.math.BigDecimal; +import java.math.RoundingMode; import java.nio.charset.Charset; import java.util.List; import java.util.function.Consumer; @@ -64,7 +65,7 @@ public void afterRow(int row) { if (committer != null) { Long[] blocks = new Long[blockIndex + 1]; for (int i = 0; i <= blockIndex; i++) { - blocks[i] = Long.valueOf(i); + blocks[i] = (long) i; } committer.accept(blocks); } @@ -91,7 +92,7 @@ public void allocateNew(int blockSize) { ((FixedWidthVector) vector).allocateNew(blockSize); } else if (vector instanceof VariableWidthVector) { VariableWidthVector variableWidthVector = (VariableWidthVector) vector; - variableWidthVector.allocateNew(varcharValueSize * blockSize, blockSize); + variableWidthVector.allocateNew((long) varcharValueSize * blockSize, blockSize); valueCapacities[i] = variableWidthVector.getValueCapacity(); } else { throw new JSONException("TODO"); @@ -150,7 +151,7 @@ public void accept(int row, int column, byte[] bytes, int off, int len, Charset Decimal256Vector decimalVector = (Decimal256Vector) vector; int scale = decimalVector.getScale(); if (decimal.scale() != scale) { - decimal = decimal.setScale(scale); + decimal = decimal.setScale(scale, RoundingMode.CEILING); } decimalVector.set(row, decimal); return; @@ -195,7 +196,7 @@ public void accept(int row, int column, byte[] bytes, int off, int len, Charset if (vector instanceof BitVector) { Boolean value = TypeUtils.parseBoolean(bytes, off, len); if (value != null) { - int intValue = value.booleanValue() ? 1 : 0; + int intValue = value ? 1 : 0; ((BitVector) vector).set(row, intValue); } return; diff --git a/extension/src/main/java/com/alibaba/fastjson2/support/arrow/ArrowUtils.java b/extension/src/main/java/com/alibaba/fastjson2/support/arrow/ArrowUtils.java index 202dba3b7e..f19118e1d7 100644 --- a/extension/src/main/java/com/alibaba/fastjson2/support/arrow/ArrowUtils.java +++ b/extension/src/main/java/com/alibaba/fastjson2/support/arrow/ArrowUtils.java @@ -10,6 +10,7 @@ import java.io.IOException; import java.math.BigDecimal; +import java.math.RoundingMode; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.util.List; @@ -167,11 +168,9 @@ public static void setValue(FieldVector vector, int row, String value) { } if (vector instanceof BitVector) { - Boolean booleanValue = Boolean.parseBoolean(value); - if (value != null) { - int intValue = booleanValue.booleanValue() ? 1 : 0; - ((BitVector) vector).set(row, intValue); - } + boolean booleanValue = Boolean.parseBoolean(value); + int intValue = booleanValue ? 1 : 0; + ((BitVector) vector).set(row, intValue); return; } @@ -180,7 +179,7 @@ public static void setValue(FieldVector vector, int row, String value) { Decimal256Vector decimalVector = (Decimal256Vector) vector; int scale = decimalVector.getScale(); if (decimal.scale() != scale) { - decimal = decimal.setScale(scale); + decimal = decimal.setScale(scale, RoundingMode.CEILING); } decimalVector.set(row, decimal); return; @@ -190,7 +189,7 @@ public static void setValue(FieldVector vector, int row, String value) { } public static void setDecimal(DecimalVector vector, int row, String str) { - if (str == null || str.length() == 0) { + if (str == null || str.isEmpty()) { vector.setNull(row); return; } @@ -296,7 +295,7 @@ public static void setDecimal(DecimalVector vector, int row, char[] bytes, int o BigDecimal decimal = BigDecimal.valueOf(unscaleValue, scale); if (vector.getScale() != decimal.scale()) { - decimal = decimal.setScale(vector.getScale(), BigDecimal.ROUND_CEILING); + decimal = decimal.setScale(vector.getScale(), RoundingMode.CEILING); } vector.set(row, decimal); return; @@ -305,7 +304,7 @@ public static void setDecimal(DecimalVector vector, int row, char[] bytes, int o BigDecimal decimal = TypeUtils.parseBigDecimal(bytes, off, len); if (vector.getScale() != decimal.scale()) { - decimal = decimal.setScale(vector.getScale(), BigDecimal.ROUND_CEILING); + decimal = decimal.setScale(vector.getScale(), RoundingMode.CEILING); } vector.set(row, decimal); } @@ -386,7 +385,7 @@ public static void setDecimal(DecimalVector vector, int row, byte[] bytes, int o BigDecimal decimal = BigDecimal.valueOf(unscaleValue, scale); if (vector.getScale() != decimal.scale()) { - decimal = decimal.setScale(vector.getScale(), BigDecimal.ROUND_CEILING); + decimal = decimal.setScale(vector.getScale(), RoundingMode.CEILING); } vector.set(row, decimal); return; @@ -395,7 +394,7 @@ public static void setDecimal(DecimalVector vector, int row, byte[] bytes, int o BigDecimal decimal = TypeUtils.parseBigDecimal(bytes, off, len); if (vector.getScale() != decimal.scale()) { - decimal = decimal.setScale(vector.getScale(), BigDecimal.ROUND_CEILING); + decimal = decimal.setScale(vector.getScale(), RoundingMode.CEILING); } vector.set(row, decimal); } @@ -403,7 +402,7 @@ public static void setDecimal(DecimalVector vector, int row, byte[] bytes, int o public static void setDecimal(DecimalVector vector, int row, BigDecimal decimal) { int scale = vector.getScale(); if (decimal.scale() != scale) { - decimal = decimal.setScale(scale, BigDecimal.ROUND_CEILING); + decimal = decimal.setScale(scale, RoundingMode.CEILING); } int precision = decimal.precision(); if (precision < 19 && FIELD_DECIMAL_INT_COMPACT_OFFSET != -1) { diff --git a/extension/src/main/java/com/alibaba/fastjson2/support/arrow/CSVUtils.java b/extension/src/main/java/com/alibaba/fastjson2/support/arrow/CSVUtils.java index 64c76a00bb..8aa8512d4f 100644 --- a/extension/src/main/java/com/alibaba/fastjson2/support/arrow/CSVUtils.java +++ b/extension/src/main/java/com/alibaba/fastjson2/support/arrow/CSVUtils.java @@ -22,7 +22,7 @@ public static String genMaxComputeCreateTable(File file, String tableName) throw String columnName; { - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); for (int j = 0; j < columnStat.name.length(); j++) { char ch = columnStat.name.charAt(j); if (ch == 0xFFFD) { @@ -62,7 +62,7 @@ public static String genMaxComputeCreateTable(File file, String tableName) throw sql.append('\t'); if (special) { - sql.append("COL_" + i); + sql.append("COL_").append(i); } else { sql.append(columnName); } diff --git a/extension/src/main/java/com/alibaba/fastjson2/support/geo/Feature.java b/extension/src/main/java/com/alibaba/fastjson2/support/geo/Feature.java index 8e7618965c..61fd4da7a2 100644 --- a/extension/src/main/java/com/alibaba/fastjson2/support/geo/Feature.java +++ b/extension/src/main/java/com/alibaba/fastjson2/support/geo/Feature.java @@ -13,7 +13,7 @@ public class Feature extends Geometry { private String id; private Geometry geometry; - private Map properties = new LinkedHashMap(); + private Map properties = new LinkedHashMap<>(); public Feature() { super("Feature"); } diff --git a/extension/src/main/java/com/alibaba/fastjson2/support/geo/FeatureCollection.java b/extension/src/main/java/com/alibaba/fastjson2/support/geo/FeatureCollection.java index ce60227073..c184676b47 100644 --- a/extension/src/main/java/com/alibaba/fastjson2/support/geo/FeatureCollection.java +++ b/extension/src/main/java/com/alibaba/fastjson2/support/geo/FeatureCollection.java @@ -11,7 +11,7 @@ @JSONType(typeName = "FeatureCollection", orders = {"type", "bbox", "coordinates"}) public class FeatureCollection extends Geometry { - private List features = new ArrayList(); + private List features = new ArrayList<>(); public FeatureCollection() { super("FeatureCollection"); } diff --git a/extension/src/main/java/com/alibaba/fastjson2/support/geo/GeometryCollection.java b/extension/src/main/java/com/alibaba/fastjson2/support/geo/GeometryCollection.java index a3e5c95b75..43c4832c43 100644 --- a/extension/src/main/java/com/alibaba/fastjson2/support/geo/GeometryCollection.java +++ b/extension/src/main/java/com/alibaba/fastjson2/support/geo/GeometryCollection.java @@ -11,7 +11,7 @@ @JSONType(typeName = "GeometryCollection", orders = {"type", "bbox", "geometries"}) public class GeometryCollection extends Geometry { - private List geometries = new ArrayList(); + private List geometries = new ArrayList<>(); public GeometryCollection() { super("GeometryCollection"); } diff --git a/extension/src/main/java/com/alibaba/fastjson2/support/redission/JSONBCodec.java b/extension/src/main/java/com/alibaba/fastjson2/support/redission/JSONBCodec.java index 81d5239412..59601011ef 100644 --- a/extension/src/main/java/com/alibaba/fastjson2/support/redission/JSONBCodec.java +++ b/extension/src/main/java/com/alibaba/fastjson2/support/redission/JSONBCodec.java @@ -99,7 +99,7 @@ public ByteBuf encode(Object object) throws IOException { } } - static final class JSONBDecoder + protected static final class JSONBDecoder implements Decoder { final JSONReader.Context context; final Type valueType; diff --git a/extension/src/main/java/com/alibaba/fastjson2/support/retrofit/Retrofit2ConverterFactory.java b/extension/src/main/java/com/alibaba/fastjson2/support/retrofit/Retrofit2ConverterFactory.java index 471a88402f..1272ec2dd0 100644 --- a/extension/src/main/java/com/alibaba/fastjson2/support/retrofit/Retrofit2ConverterFactory.java +++ b/extension/src/main/java/com/alibaba/fastjson2/support/retrofit/Retrofit2ConverterFactory.java @@ -52,7 +52,7 @@ public Converter responseBodyConverter( Annotation[] annotations, Retrofit retrofit ) { - return new ResponseBodyConverter(type); + return new ResponseBodyConverter<>(type); } @Override @@ -62,7 +62,7 @@ public Converter requestBodyConverter( Annotation[] methodAnnotations, Retrofit retrofit ) { - return new RequestBodyConverter(); + return new RequestBodyConverter<>(); } public FastJsonConfig getFastJsonConfig() { diff --git a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSON.java b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSON.java index 105fc64be2..a02a507e88 100644 --- a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSON.java +++ b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSON.java @@ -9,7 +9,6 @@ import com.alibaba.fastjson2.JSONFactory; import com.alibaba.fastjson2.JSONReader; import com.alibaba.fastjson2.JSONWriter; -import com.alibaba.fastjson2.filter.Filter; import com.alibaba.fastjson2.filter.PropertyFilter; import com.alibaba.fastjson2.filter.PropertyPreFilter; import com.alibaba.fastjson2.filter.ValueFilter; @@ -514,14 +513,13 @@ public static T parseObject(String str, Class objectClass, ParseProcess p } } - @SuppressWarnings("unchecked") public static T parseObject(String str, TypeReference typeReference, Feature... features) { Type type = typeReference != null ? typeReference.getType() : Object.class; - return (T) parseObject(str, type, features); + return parseObject(str, type, features); } public static T parseObject(String input, Type clazz, int featureValues, Feature... features) { - return (T) parseObject(input, clazz, ParserConfig.global, featureValues, features); + return parseObject(input, clazz, ParserConfig.global, featureValues, features); } public static T parseObject(String str, Class objectClass) { @@ -723,7 +721,7 @@ public static T parseObject( ParserConfig config, Feature... features ) throws IOException { - return (T) parseObject(is, charset, type, config, null, DEFAULT_PARSER_FEATURE, features); + return parseObject(is, charset, type, config, null, DEFAULT_PARSER_FEATURE, features); } public static T parseObject( @@ -763,7 +761,7 @@ public static T parseObject( /** * @since 2.0.7 */ - public static JSONObject parseObject(byte[] jsonBytes, Feature... features) { + public static JSONObject parseObject(byte[] jsonBytes, Feature... features) { if (jsonBytes == null || jsonBytes.length == 0) { return null; } @@ -896,8 +894,8 @@ public static T parseObject(byte[] jsonBytes, Type type, SerializeFilter fil try { JSONReader jsonReader = JSONReader.of(jsonBytes, context); - if (filter instanceof Filter) { - context.config((Filter) filter); + if (filter != null) { + context.config(filter); } ObjectReader objectReader = jsonReader.getObjectReader(type); @@ -1134,7 +1132,6 @@ public static Object parse(byte[] input, int off, int len, CharsetDecoder charse } } - @SuppressWarnings("unchecked") public static T parseObject( byte[] input, int off, @@ -1608,7 +1605,7 @@ public static byte[] toJSONBytes(Object object, SerializeConfig config, Serializ public static String toJSONString(Object object, boolean prettyFormat) { SerializerFeature[] features = prettyFormat ? new SerializerFeature[]{SerializerFeature.PrettyFormat} - : new SerializerFeature[0]; + : SerializerFeature.EMPTY; JSONWriter.Context context = createWriteContext(SerializeConfig.global, DEFAULT_GENERATE_FEATURE, features); @@ -1726,7 +1723,7 @@ public static byte[] toJSONBytes(Object object) { } public static byte[] toJSONBytes(Object object, SerializeFilter... filters) { - return toJSONBytes(object, filters, new SerializerFeature[0]); + return toJSONBytes(object, filters, SerializerFeature.EMPTY); } public static byte[] toJSONBytes(Object object, int defaultFeatures, SerializerFeature... features) { @@ -1945,7 +1942,7 @@ public static final int writeJSONString( OutputStream os, Object object, SerializeFilter[] filters) throws IOException { - return writeJSONString(os, object, filters, new SerializerFeature[0]); + return writeJSONString(os, object, filters, SerializerFeature.EMPTY); } public static final int writeJSONString( @@ -2295,7 +2292,7 @@ public T toJavaObject(TypeReference typeReference) { public static T toJavaObject(JSON json, Class clazz) { if (json instanceof JSONObject) { - return ((JSONObject) json).toJavaObject(clazz); + return json.toJavaObject(clazz); } String str = toJSONString(json); diff --git a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSONArray.java b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSONArray.java index e9ee4fe012..a9eed4ead1 100644 --- a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSONArray.java +++ b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSONArray.java @@ -192,12 +192,12 @@ public BigDecimal getBigDecimal(int index) { } if (value instanceof Float) { - float floatValue = ((Float) value).floatValue(); + float floatValue = (Float) value; return toBigDecimal(floatValue); } if (value instanceof Double) { - double doubleValue = ((Double) value).doubleValue(); + double doubleValue = (Double) value; return toBigDecimal(doubleValue); } @@ -821,7 +821,7 @@ public T getObject(int index, Type type) { return (T) TypeUtils.cast(obj, (Class) type); } else { String json = JSON.toJSONString(obj); - return (T) JSON.parseObject(json, type); + return JSON.parseObject(json, type); } } @@ -856,7 +856,7 @@ public T getObject(int index, Class clazz) { } public List toJavaList(Class clazz) { - List list = new ArrayList(this.size()); + List list = new ArrayList<>(this.size()); ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider(); ObjectReader objectReader = provider.getObjectReader(clazz); @@ -877,10 +877,8 @@ public List toJavaList(Class clazz) { list.add((T) converted); continue; } - - throw new com.alibaba.fastjson2.JSONException( - (item == null ? "null" : item.getClass()) + " cannot be converted to " + clazz - ); + // item is NOT null here + throw new com.alibaba.fastjson2.JSONException(item.getClass() + " cannot be converted to " + clazz); } list.add(classItem); } diff --git a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSONObject.java b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSONObject.java index 2bcf308a92..bd0b7ceb99 100755 --- a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSONObject.java +++ b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSONObject.java @@ -78,9 +78,9 @@ public JSONObject(int initialCapacity) { public JSONObject(int initialCapacity, boolean ordered) { if (ordered) { - map = new LinkedHashMap(initialCapacity); + map = new LinkedHashMap<>(initialCapacity); } else { - map = new HashMap(initialCapacity); + map = new HashMap<>(initialCapacity); } } @@ -425,7 +425,7 @@ public boolean getBooleanValue(String key) { return false; } - return booleanVal.booleanValue(); + return booleanVal; } public byte getByteValue(String key) { @@ -751,12 +751,12 @@ public BigDecimal getBigDecimal(String key) { } if (value instanceof Float) { - float floatValue = ((Float) value).floatValue(); + float floatValue = (Float) value; return toBigDecimal(floatValue); } if (value instanceof Double) { - double doubleValue = ((Double) value).doubleValue(); + double doubleValue = (Double) value; return toBigDecimal(doubleValue); } @@ -856,11 +856,11 @@ public JSONObject fluentPut(String key, Object value) { } @Override - public void putAll(Map m) { + public void putAll(Map m) { map.putAll(m); } - public JSONObject fluentPutAll(Map m) { + public JSONObject fluentPutAll(Map m) { map.putAll(m); return this; } @@ -903,8 +903,8 @@ public Set> entrySet() { @Override public Object clone() { return new JSONObject(map instanceof LinkedHashMap // - ? new LinkedHashMap(map) // - : new HashMap(map) + ? new LinkedHashMap<>(map) // + : new HashMap<>(map) ); } diff --git a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSONPObject.java b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSONPObject.java index f3d8765af3..9a27f3c5ec 100644 --- a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSONPObject.java +++ b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSONPObject.java @@ -5,7 +5,7 @@ public class JSONPObject extends com.alibaba.fastjson2.JSONPObject { - private final List parameters = new ArrayList(); + private final List parameters = new ArrayList<>(); public JSONPObject() { } diff --git a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSONPath.java b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSONPath.java index 20a8958c6a..2908bb4bf0 100644 --- a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSONPath.java +++ b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/JSONPath.java @@ -51,21 +51,20 @@ public static T read(String json, String path, Type clazz) { public static Object eval(String rootObject, String path) { Object result = com.alibaba.fastjson2.JSONPath.eval(rootObject, path); - if (result instanceof com.alibaba.fastjson2.JSONArray) { - result = new com.alibaba.fastjson.JSONArray((com.alibaba.fastjson2.JSONArray) result); - } else if (result instanceof com.alibaba.fastjson2.JSONObject) { - result = new com.alibaba.fastjson.JSONObject((com.alibaba.fastjson2.JSONObject) result); - } - return result; + return adaptResult(result); } public static Object eval(Object rootObject, String path) { com.alibaba.fastjson2.JSONPath jsonPath = com.alibaba.fastjson2.JSONPath.of(path); Object result = jsonPath.eval(rootObject); + return adaptResult(result); + } + + private static Object adaptResult(Object result) { if (result instanceof com.alibaba.fastjson2.JSONArray) { - result = new com.alibaba.fastjson.JSONArray((com.alibaba.fastjson2.JSONArray) result); + result = new JSONArray((com.alibaba.fastjson2.JSONArray) result); } else if (result instanceof com.alibaba.fastjson2.JSONObject) { - result = new com.alibaba.fastjson.JSONObject((com.alibaba.fastjson2.JSONObject) result); + result = new JSONObject((com.alibaba.fastjson2.JSONObject) result); } return result; } @@ -91,12 +90,7 @@ public static Object extract(String json, String path) { JSONReader.Context context = JSON.createReadContext(JSON.DEFAULT_PARSER_FEATURE); JSONReader jsonReader = JSONReader.of(json, context); Object result = jsonPath.extract(jsonReader); - if (result instanceof com.alibaba.fastjson2.JSONArray) { - result = new com.alibaba.fastjson.JSONArray((com.alibaba.fastjson2.JSONArray) result); - } else if (result instanceof com.alibaba.fastjson2.JSONObject) { - result = new com.alibaba.fastjson.JSONObject((com.alibaba.fastjson2.JSONObject) result); - } - return result; + return adaptResult(result); } public static boolean remove(Object root, String path) { diff --git a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/TypeReference.java b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/TypeReference.java index 9fe770a835..bf9a24b114 100755 --- a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/TypeReference.java +++ b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/TypeReference.java @@ -27,7 +27,7 @@ */ public class TypeReference { static ConcurrentMap classTypeCache - = new ConcurrentHashMap(16, 0.75f, 1); + = new ConcurrentHashMap<>(16, 0.75f, 1); protected final Type type; diff --git a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonProvider.java b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonProvider.java index 8ae5de1e99..492048c9b9 100644 --- a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonProvider.java +++ b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/support/jaxrs/FastJsonProvider.java @@ -17,6 +17,7 @@ import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -55,10 +56,10 @@ public class FastJsonProvider }; @Deprecated - protected Charset charset = Charset.forName("UTF-8"); + protected Charset charset = StandardCharsets.UTF_8; @Deprecated - protected SerializerFeature[] features = new SerializerFeature[0]; + protected SerializerFeature[] features = SerializerFeature.EMPTY; @Deprecated protected SerializeFilter[] filters = new SerializeFilter[0]; @@ -358,7 +359,7 @@ public void writeTo( if (serializerFeatures == null) { serializerFeatures = new SerializerFeature[]{SerializerFeature.PrettyFormat}; } else { - List featureList = new ArrayList(Arrays.asList(serializerFeatures)); + List featureList = new ArrayList<>(Arrays.asList(serializerFeatures)); featureList.add(SerializerFeature.PrettyFormat); serializerFeatures = featureList.toArray(serializerFeatures); } @@ -397,10 +398,8 @@ static final int writeJSONStringWithFastJsonConfig( } JSONWriter.Context context = JSON.createWriteContext(config, defaultFeatures, features); - com.alibaba.fastjson2.JSONWriter writer = com.alibaba.fastjson2.JSONWriter.ofUTF8(context); context.setDateFormat(dateFormat); - - try { + try (JSONWriter writer = JSONWriter.ofUTF8(context)) { if (filters != null) { for (SerializeFilter filter : filters) { JSON.configFilter(context, filter); @@ -409,10 +408,7 @@ static final int writeJSONStringWithFastJsonConfig( writer.writeAny(object); - int len = writer.flushTo(os, charset); - return len; - } finally { - writer.close(); + return writer.flushTo(os, charset); } } diff --git a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/support/spring/FastJsonJsonView.java b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/support/spring/FastJsonJsonView.java index a699c3df10..089afca69d 100644 --- a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/support/spring/FastJsonJsonView.java +++ b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/support/spring/FastJsonJsonView.java @@ -17,6 +17,7 @@ import java.io.ByteArrayOutputStream; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -48,10 +49,10 @@ public class FastJsonJsonView private static final Pattern CALLBACK_PARAM_PATTERN = Pattern.compile("[0-9A-Za-z_\\.]*"); @Deprecated - protected Charset charset = Charset.forName("UTF-8"); + protected Charset charset = StandardCharsets.UTF_8; @Deprecated - protected SerializerFeature[] features = new SerializerFeature[0]; + protected SerializerFeature[] features = SerializerFeature.EMPTY; @Deprecated protected SerializeFilter[] filters = new SerializeFilter[0]; @@ -359,7 +360,7 @@ public void setUpdateContentLength(boolean updateContentLength) { * @return the object to be rendered */ protected Object filterModel(Map model) { - Map result = new HashMap(model.size()); + Map result = new HashMap<>(model.size()); Set renderedAttributes = !CollectionUtils.isEmpty(this.renderedAttributes) ? // this.renderedAttributes // : model.keySet(); diff --git a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/support/spring/PropertyPreFilters.java b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/support/spring/PropertyPreFilters.java index 7971b812e5..5cbb918a60 100644 --- a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/support/spring/PropertyPreFilters.java +++ b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/support/spring/PropertyPreFilters.java @@ -12,7 +12,7 @@ * @author liuming */ public class PropertyPreFilters { - private List filters = new ArrayList(); + private List filters = new ArrayList<>(); public MySimplePropertyPreFilter addFilter() { MySimplePropertyPreFilter filter = new MySimplePropertyPreFilter(); diff --git a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/support/spring/annotation/FastJsonView.java b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/support/spring/annotation/FastJsonView.java index 209a776974..d1465abf88 100644 --- a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/support/spring/annotation/FastJsonView.java +++ b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/support/spring/annotation/FastJsonView.java @@ -163,7 +163,7 @@ public void setUpdateContentLength(boolean updateContentLength) { * @return the object to be rendered */ protected Object filterModel(Map model) { - Map result = new HashMap(model.size()); + Map result = new HashMap<>(model.size()); Set renderedAttributes = !CollectionUtils.isEmpty(this.renderedAttributes) ? // this.renderedAttributes // : model.keySet(); diff --git a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/util/FieldInfo.java b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/util/FieldInfo.java index e9ad13214e..ab666fb221 100644 --- a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/util/FieldInfo.java +++ b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/util/FieldInfo.java @@ -110,11 +110,11 @@ public FieldInfo( nameHashCode = nameHashCode64(name, annotation); - boolean jsonDirect = false; + boolean jsonDirect; if (annotation != null) { format = annotation.format(); - if (format.trim().length() == 0) { + if (format.trim().isEmpty()) { format = null; } jsonDirect = annotation.jsonDirect(); @@ -288,7 +288,7 @@ public static Type getFieldType( } private static boolean getArgument(Type[] typeArgs, Map genericInfo) { - if (genericInfo == null || genericInfo.size() == 0) { + if (genericInfo == null || genericInfo.isEmpty()) { return false; } boolean changed = false; @@ -305,8 +305,9 @@ private static boolean getArgument(Type[] typeArgs, Map gene changed = true; } } else if (typeArg instanceof TypeVariable) { - if (genericInfo.containsKey(typeArg)) { - typeArgs[i] = genericInfo.get(typeArg); + Type type = genericInfo.get(typeArg); + if (type != null) { // genericInfo should NOT contain null value + typeArgs[i] = type; changed = true; } } diff --git a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/util/TypeUtils.java b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/util/TypeUtils.java index e79942c9a4..5762796d8f 100755 --- a/fastjson1-compatible/src/main/java/com/alibaba/fastjson/util/TypeUtils.java +++ b/fastjson1-compatible/src/main/java/com/alibaba/fastjson/util/TypeUtils.java @@ -35,8 +35,6 @@ import java.math.BigInteger; import java.sql.Timestamp; import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; /** * @author wenshao[szujobs@hotmail.com] @@ -59,14 +57,10 @@ public class TypeUtils { private static volatile boolean kotlin_error; private static volatile Map kotlinIgnores; private static volatile boolean kotlinIgnores_error; - private static ConcurrentMap> mappings = new ConcurrentHashMap>(256, 0.75f, 1); - private static Class pathClass; - private static boolean PATH_CLASS_ERROR; private static boolean transientClassInited; private static Class transientClass; - @SuppressWarnings({"unchecked", "rawtypes"}) public static T cast(Object obj, Class clazz, ParserConfig config) { return com.alibaba.fastjson2.util.TypeUtils.cast(obj, clazz, config.getProvider()); } @@ -102,72 +96,42 @@ public static T cast(Object obj, Type type, ParserConfig mapping) { @SuppressWarnings({"rawtypes", "unchecked"}) public static T cast(Object obj, ParameterizedType type, ParserConfig mapping) { - Type rawTye = type.getRawType(); + final Type rawType = type.getRawType(); - if (rawTye == List.class || rawTye == ArrayList.class) { + if (rawType == List.class || rawType == ArrayList.class) { Type itemType = type.getActualTypeArguments()[0]; if (obj instanceof List) { List listObj = (List) obj; List arrayList = new ArrayList(listObj.size()); - for (int i = 0; i < listObj.size(); i++) { - Object item = listObj.get(i); - - Object itemValue; - if (itemType instanceof Class) { - if (item != null && item.getClass() == JSONObject.class) { - itemValue = ((JSONObject) item).toJavaObject((Class) itemType, mapping, 0); - } else { - itemValue = cast(item, (Class) itemType, mapping); - } - } else { - itemValue = cast(item, itemType, mapping); - } - - arrayList.add(itemValue); - } + castItemsTo(mapping, listObj, itemType, arrayList); return (T) arrayList; } } - if (rawTye == Set.class || rawTye == HashSet.class // - || rawTye == TreeSet.class // - || rawTye == Collection.class // - || rawTye == List.class // - || rawTye == ArrayList.class) { + if (rawType == Set.class || rawType == HashSet.class // + || rawType == TreeSet.class // + || rawType == Collection.class // + || rawType == List.class // + || rawType == ArrayList.class) { Type itemType = type.getActualTypeArguments()[0]; if (obj instanceof Iterable) { Collection collection; - if (rawTye == Set.class || rawTye == HashSet.class) { + if (rawType == Set.class || rawType == HashSet.class) { collection = new HashSet(); - } else if (rawTye == TreeSet.class) { + } else if (rawType == TreeSet.class) { collection = new TreeSet(); } else { collection = new ArrayList(); } - for (Iterator it = ((Iterable) obj).iterator(); it.hasNext(); ) { - Object item = it.next(); - - Object itemValue; - if (itemType instanceof Class) { - if (item != null && item.getClass() == JSONObject.class) { - itemValue = ((JSONObject) item).toJavaObject((Class) itemType, mapping, 0); - } else { - itemValue = cast(item, (Class) itemType, mapping); - } - } else { - itemValue = cast(item, itemType, mapping); - } - - collection.add(itemValue); - } + castItemsTo(mapping, (Iterable) obj, itemType, collection); return (T) collection; } } - if (rawTye == Map.class || rawTye == HashMap.class) { - Type keyType = type.getActualTypeArguments()[0]; - Type valueType = type.getActualTypeArguments()[1]; + if (rawType == Map.class || rawType == HashMap.class) { + final Type[] args = type.getActualTypeArguments(); + Type keyType = args[0], valueType = args[1]; if (obj instanceof Map) { Map map = new HashMap(); for (Map.Entry entry : ((Map) obj).entrySet()) { @@ -180,23 +144,24 @@ public static T cast(Object obj, ParameterizedType type, ParserConfig mappin } if (obj instanceof String) { String strVal = (String) obj; - if (strVal.length() == 0) { + if (strVal.isEmpty()) { return null; } } - if (type.getActualTypeArguments().length == 1) { - Type argType = type.getActualTypeArguments()[0]; + final Type[] args = type.getActualTypeArguments(); + if (args.length == 1) { + Type argType = args[0]; if (argType instanceof WildcardType) { - return cast(obj, rawTye, mapping); + return cast(obj, rawType, mapping); } } - if (rawTye == Map.Entry.class && obj instanceof Map && ((Map) obj).size() == 1) { + if (rawType == Map.Entry.class && obj instanceof Map && ((Map) obj).size() == 1) { Map.Entry entry = (Map.Entry) ((Map) obj).entrySet().iterator().next(); return (T) entry; } - if (rawTye instanceof Class) { + if (rawType instanceof Class) { if (mapping == null) { mapping = ParserConfig.global; } @@ -207,12 +172,29 @@ public static T cast(Object obj, ParameterizedType type, ParserConfig mappin // return (T) deserializer.deserialze(parser, type, null); // } - throw new JSONException("TODO : " + type); // TOD: cast + throw new JSONException("TODO : " + type); // TODO: cast } throw new JSONException("can not cast to : " + type); } + private static void castItemsTo(ParserConfig mapping, Iterable items, Type itemType, Collection to) { + for (Object item : items) { + Object itemValue; + if (itemType instanceof Class) { + if (item != null && item.getClass() == JSONObject.class) { + itemValue = ((JSONObject) item).toJavaObject((Class) itemType, mapping, 0); + } else { + itemValue = cast(item, (Class) itemType, mapping); + } + } else { + itemValue = cast(item, itemType, mapping); + } + + to.add(itemValue); + } + } + @SuppressWarnings("unchecked") public static T castToJavaBean(Map map, Class clazz, ParserConfig config) { try { @@ -297,8 +279,8 @@ public static T castToJavaBean(Map map, Class clazz, Pars if (innerMap instanceof LinkedHashMap) { return (T) innerMap; } else { - LinkedHashMap linkedHashMap = new LinkedHashMap(); - linkedHashMap.putAll(innerMap); + // 这里应该返回 LinkedHashMap + return (T) new LinkedHashMap(innerMap); } } @@ -465,52 +447,36 @@ public static long longExtractValue(Number number) { } public static A getAnnotation(Class targetClass, Class annotationClass) { - A targetAnnotation = targetClass.getAnnotation(annotationClass); - - Class mixInClass = null; - Type type = JSON.getMixInAnnotations(targetClass); - if (type instanceof Class) { - mixInClass = (Class) type; - } + Class mixInClass = getMixInClass(targetClass); if (mixInClass != null) { - A mixInAnnotation = mixInClass.getAnnotation(annotationClass); - Annotation[] annotations = mixInClass.getAnnotations(); - if (mixInAnnotation == null && annotations.length > 0) { - for (Annotation annotation : annotations) { - mixInAnnotation = annotation.annotationType().getAnnotation(annotationClass); - if (mixInAnnotation != null) { - break; - } - } - } + A mixInAnnotation = getAnnotationOrCandidate(mixInClass, annotationClass); if (mixInAnnotation != null) { return mixInAnnotation; } } - Annotation[] targetClassAnnotations = targetClass.getAnnotations(); - if (targetAnnotation == null && targetClassAnnotations.length > 0) { - for (Annotation annotation : targetClassAnnotations) { - targetAnnotation = annotation.annotationType().getAnnotation(annotationClass); - if (targetAnnotation != null) { + return getAnnotationOrCandidate(targetClass, annotationClass); + } + + private static A getAnnotationOrCandidate(Class clazz, Class annotationClass) { + A target = clazz.getAnnotation(annotationClass); + if (target == null) { + Annotation[] candidates = clazz.getAnnotations(); + for (Annotation annotation : candidates) { + target = annotation.annotationType().getAnnotation(annotationClass); + if (target != null) { break; } } } - return targetAnnotation; + return target; } public static A getAnnotation(Field field, Class annotationClass) { A targetAnnotation = field.getAnnotation(annotationClass); - Class clazz = field.getDeclaringClass(); - A mixInAnnotation; - Class mixInClass = null; - Type type = JSON.getMixInAnnotations(clazz); - if (type instanceof Class) { - mixInClass = (Class) type; - } + Class mixInClass = getMixInClass(field.getDeclaringClass()); if (mixInClass != null) { Field mixInField = null; @@ -527,7 +493,7 @@ public static A getAnnotation(Field field, Class annot if (mixInField == null) { return targetAnnotation; } - mixInAnnotation = mixInField.getAnnotation(annotationClass); + A mixInAnnotation = mixInField.getAnnotation(annotationClass); if (mixInAnnotation != null) { return mixInAnnotation; } @@ -535,16 +501,17 @@ public static A getAnnotation(Field field, Class annot return targetAnnotation; } - public static A getAnnotation(Method method, Class annotationClass) { - A targetAnnotation = method.getAnnotation(annotationClass); - - Class clazz = method.getDeclaringClass(); - A mixInAnnotation; - Class mixInClass = null; + private static Class getMixInClass(Class clazz) { Type type = JSON.getMixInAnnotations(clazz); + Class mixInClass = null; if (type instanceof Class) { mixInClass = (Class) type; } + return mixInClass; + } + + public static A getAnnotation(Method method, Class annotationClass) { + Class mixInClass = getMixInClass(method.getDeclaringClass()); if (mixInClass != null) { Method mixInMethod = null; @@ -559,15 +526,14 @@ public static A getAnnotation(Method method, Class ann // skip } } - if (mixInMethod == null) { - return targetAnnotation; - } - mixInAnnotation = mixInMethod.getAnnotation(annotationClass); - if (mixInAnnotation != null) { - return mixInAnnotation; + if (mixInMethod != null) { + A mixInAnnotation = mixInMethod.getAnnotation(annotationClass); + if (mixInAnnotation != null) { + return mixInAnnotation; + } } } - return targetAnnotation; + return method.getAnnotation(annotationClass); } public static Double castToDouble(Object value) { @@ -715,7 +681,7 @@ public static List computeGetters(Class clazz, Map public static List computeGetters(Class clazz, Map aliasMap, boolean sorted) { JSONType jsonType = TypeUtils.getAnnotation(clazz, JSONType.class); - Map fieldCacheMap = new HashMap(); + Map fieldCacheMap = new HashMap<>(); ParserConfig.parserAllFieldToCache(clazz, fieldCacheMap); return computeGetters(clazz, jsonType, aliasMap, fieldCacheMap, sorted, PropertyNamingStrategy.CamelCase); } @@ -727,7 +693,7 @@ public static List computeGetters(Class clazz, // boolean sorted, // PropertyNamingStrategy propertyNamingStrategy // ) { - Map fieldInfoMap = new LinkedHashMap(); + Map fieldInfoMap = new LinkedHashMap<>(); boolean kotlin = TypeUtils.isKotlin(clazz); // for kotlin Constructor[] constructors = null; @@ -776,10 +742,10 @@ public static List computeGetters(Class clazz, // if (kotlin && isKotlinIgnore(clazz, methodName)) { continue; } - /** + /* * 如果在属性或者方法上存在JSONField注解,并且定制了name属性,不以类上的propertyNamingStrategy设置为准,以此字段的JSONField的name定制为准。 */ - Boolean fieldAnnotationAndNameExists = false; + boolean fieldAnnotationAndNameExists = false; JSONField annotation = TypeUtils.getAnnotation(method, JSONField.class); if (annotation == null) { annotation = getSuperMethodAnnotation(clazz, method); @@ -1114,14 +1080,14 @@ private static void computeFields( } private static List getFieldInfos(Class clazz, boolean sorted, Map fieldInfoMap) { - List fieldInfoList = new ArrayList(); + List fieldInfoList = new ArrayList<>(); String[] orders = 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()); + LinkedHashMap map = new LinkedHashMap<>(fieldInfoMap.size()); for (FieldInfo field : fieldInfoMap.values()) { map.put(field.name, field); } @@ -1178,8 +1144,8 @@ public static Constructor getKotlinConstructor(Constructor[] constructors, Strin if (paramNames != null && parameterTypes.length != paramNames.length) { continue; } - - if (parameterTypes.length > 0 && "kotlin.jvm.internal.DefaultConstructorMarker".equals(parameterTypes[parameterTypes.length - 1])) { + // String equals to Class will always return false ! + if (parameterTypes.length > 0 && "kotlin.jvm.internal.DefaultConstructorMarker".equals(parameterTypes[parameterTypes.length - 1].getName())) { continue; } if (creatorConstructor != null && creatorConstructor.getParameterTypes().length >= parameterTypes.length) { @@ -1238,7 +1204,7 @@ public static String[] getKoltinConstructorParameters(Class clazz) { 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();) { Object item = iterator.next(); List parameters = (List) kotlin_kfunction_getParameters.invoke(item); if (constructor != null && parameters.size() == 0) { @@ -1268,7 +1234,7 @@ public static String[] getKoltinConstructorParameters(Class clazz) { static boolean isKotlinIgnore(Class clazz, String methodName) { if (kotlinIgnores == null && !kotlinIgnores_error) { try { - Map map = new HashMap(); + Map map = new HashMap<>(); Class charRangeClass = Class.forName("kotlin.ranges.CharRange"); map.put(charRangeClass, new String[]{"getEndInclusive", "isEmpty"}); Class intRangeClass = Class.forName("kotlin.ranges.IntRange"); @@ -1417,21 +1383,15 @@ public static String getPropertyNameByMethodName(String methodName) { } public static Annotation[][] getParameterAnnotations(Constructor constructor) { - Annotation[][] targetAnnotations = constructor.getParameterAnnotations(); - Class clazz = constructor.getDeclaringClass(); - Annotation[][] mixInAnnotations; - Class mixInClass = null; - Type type = JSON.getMixInAnnotations(clazz); - if (type instanceof Class) { - mixInClass = (Class) type; - } + + Class mixInClass = getMixInClass(clazz); if (mixInClass != null) { Constructor mixInConstructor = null; Class[] parameterTypes = constructor.getParameterTypes(); // 构建参数列表,因为内部类的构造函数需要传入外部类的引用 - List> enclosingClasses = new ArrayList>(2); + List> enclosingClasses = new ArrayList<>(2); for (Class enclosingClass = mixInClass.getEnclosingClass(); enclosingClass != null; enclosingClass = enclosingClass.getEnclosingClass()) { enclosingClasses.add(enclosingClass); } @@ -1454,15 +1414,15 @@ public static Annotation[][] getParameterAnnotations(Constructor constructor) { level--; } } - if (mixInConstructor == null) { - return targetAnnotations; - } - mixInAnnotations = mixInConstructor.getParameterAnnotations(); - if (mixInAnnotations != null) { - return mixInAnnotations; + if (mixInConstructor != null) { + // mixInAnnotations is non-null, but length may be 0 + Annotation[][] mixInAnnotations = mixInConstructor.getParameterAnnotations(); + if (mixInAnnotations.length == 0) { + return mixInAnnotations; + } } } - return targetAnnotations; + return constructor.getParameterAnnotations(); } public static class MethodInheritanceComparator