Improve some code, fix some bugs (#3320)

* Unified setting file encoding to UTF-8

* Fix issue#3283

* Aligning with new features of JDK8

* Simply some redundant code

* Improve Map handle performance

* Fix some potential bugs

* Improve some String processing performance

* Remove unnecessary protected modifier from final classes, because they are NOT inheritable

* Aligning with new features of JDK8

* Optimize FastJsonJsonView

* Fix conditional branch duplication

* Revert "Unified setting file encoding to UTF-8"

This reverts commit 66f1238da8371886a38473dbe8d5374e87e85381.
This commit is contained in:
CodePlayer 2025-01-25 15:06:57 +08:00 committed by GitHub
parent e77736f838
commit 3016e80649
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
60 changed files with 382 additions and 563 deletions

View File

@ -168,9 +168,9 @@ public class Analysis {
}
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 @@ public class Analysis {
}
private List<TypeElement> getTypeHierarchy(TypeElement element) {
List<TypeElement> result = new ArrayList<TypeElement>();
getAllTypes(element, result, new HashSet<TypeElement>());
List<TypeElement> result = new ArrayList<>();
getAllTypes(element, result, new HashSet<>());
return result;
}

View File

@ -495,7 +495,7 @@ public class CodeGenUtils {
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;

View File

@ -1410,7 +1410,7 @@ abstract class JSONPathSegment {
action.accept(object);
}
protected boolean shouldRecursive() {
boolean shouldRecursive() {
return nameHashCode == HASH_STAR || nameHashCode == HASH_EMPTY;
}

View File

@ -2163,7 +2163,7 @@ public abstract class JSONReader
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);

View File

@ -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 @@ final class JSONReaderJSONB
return hashCode;
}
protected long getNameHashCode() {
long getNameHashCode() {
int offset = strBegin;
long nameValue = 0;
for (int i = 0; i < strlen; offset++) {
@ -3774,7 +3774,7 @@ final class JSONReaderJSONB
return int64Value;
}
protected String readFixedAsciiString(int strlen) {
String readFixedAsciiString(int strlen) {
byte[] bytes = this.bytes;
int offset = this.offset;
String str;

View File

@ -2474,7 +2474,7 @@ class JSONReaderUTF16
}
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 @@ class JSONReaderUTF16
}
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 @@ class JSONReaderUTF16
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;

View File

@ -7152,9 +7152,9 @@ class JSONReaderUTF8
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;

View File

@ -2,7 +2,6 @@ package com.alibaba.fastjson2;
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

View File

@ -30,7 +30,7 @@ public abstract class DateTimeCodec {
public DateTimeCodec(String format, Locale locale) {
if (format != null) {
format = format.replaceAll("aa", "a");
format = format.replace("aa", "a");
}
this.format = format;

View File

@ -9,7 +9,7 @@ public class TypeCollector {
static final Map<String, String> PRIMITIVES;
static {
HashMap map = new HashMap();
HashMap<String, String> map = new HashMap<>();
map.put("int", "I");
map.put("boolean", "Z");
map.put("byte", "B");
@ -75,21 +75,22 @@ public class TypeCollector {
// }
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() {

View File

@ -70,10 +70,6 @@ class FieldReaderCollectionMethodReadOnly<T>
return;
}
if (value == collection) {
return;
}
Collection values = (Collection) value;
for (Object item : values) {
if (item == null) {

View File

@ -1122,7 +1122,7 @@ public class ObjectReaderBaseModule
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 @@ public class ObjectReaderBaseModule
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 @@ public class ObjectReaderBaseModule
if (fieldInfo.alternateNames == null) {
fieldInfo.alternateNames = alternateNames;
} else {
Set<String> nameSet = new LinkedHashSet<>();
nameSet.addAll(Arrays.asList(alternateNames));
nameSet.addAll(Arrays.asList(fieldInfo.alternateNames));
Set<String> 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()]);
}
}

View File

@ -724,27 +724,26 @@ public class ObjectReaderCreator {
boolean[] flags = null;
int maskCount = 0;
if (setterFieldReaders != null) {
// 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++) {
FieldReader setterFieldReader = setterFieldReaders[i];
if (fieldReaders.containsKey(setterFieldReader.fieldName)) {
if (flags == null) {
flags = new boolean[setterFieldReaders.length];
}
flags[i] = true;
maskCount++;
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<T>) new ObjectReaderNoneDefaultConstructor(

View File

@ -336,10 +336,7 @@ public class ObjectReaderNoneDefaultConstructor<T>
}
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);
}
}
}

View File

@ -12,8 +12,8 @@ import java.util.function.Supplier;
public final class ObjectReaderRootName<T>
extends ObjectReaderAdapter<T> {
protected final String rootName;
protected final long rootNameHashCode;
final String rootName;
final long rootNameHashCode;
public ObjectReaderRootName(
Class objectClass,

View File

@ -329,18 +329,7 @@ public final class ArraySchema
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

View File

@ -641,6 +641,10 @@ public abstract class JSONSchema {
static AnyOf anyOf(JSONObject input, Class type) {
JSONArray array = input.getJSONArray("anyOf");
return anyOf(array, type);
}
static JSONSchema[] makeSchemaItems(JSONArray array, Class type) {
if (array == null || array.isEmpty()) {
return null;
}
@ -648,58 +652,28 @@ public abstract class JSONSchema {
for (int i = 0; i < items.length; i++) {
items[i] = JSONSchema.of(array.getJSONObject(i), type);
}
return new AnyOf(items);
return items;
}
static AnyOf anyOf(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 AnyOf(items);
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 abstract class JSONSchema {
public void accept(Predicate<JSONSchema> 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;
}
}

View File

@ -673,19 +673,7 @@ public final class ObjectSchema
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<JSONSchema> v) {

View File

@ -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<String>) enums);
} else if (property instanceof Object[]) {
enumValues = input.getObject("enum", TypeReference.collectionType(LinkedHashSet.class, String.class));

View File

@ -1053,7 +1053,7 @@ public class DateUtils {
} 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 class DateUtils {
} 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 class DateUtils {
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 class DateUtils {
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 class DateUtils {
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 @@ public class DateUtils {
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 @@ public class DateUtils {
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 class DateUtils {
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 class DateUtils {
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 class DateUtils {
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 class DateUtils {
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 class DateUtils {
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

View File

@ -164,7 +164,7 @@ public final class FDBigInteger {
}
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 @@ public final class FDBigInteger {
}
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;

View File

@ -1037,10 +1037,8 @@ public class IOUtils {
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++, '-');

View File

@ -1001,7 +1001,7 @@ public class TypeUtils {
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 class TypeUtils {
return cast(obj, type, JSONFactory.getDefaultObjectReaderProvider());
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T cast(Object obj, Type type, ObjectReaderProvider provider) {
if (type instanceof Class) {
return (T) cast(obj, (Class) type, provider);
return cast(obj, (Class<T>) type, provider);
}
if (obj instanceof Collection) {
@ -1429,6 +1430,7 @@ public class TypeUtils {
return cast(obj, targetClass, JSONFactory.getDefaultObjectReaderProvider());
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T cast(Object obj, Class<T> targetClass, ObjectReaderProvider provider) {
if (obj == null) {
return null;

View File

@ -980,7 +980,7 @@ public class ObjectWriterBaseModule
jsonFieldFormat = jsonFieldFormat.trim();
if (jsonFieldFormat.indexOf('T') != -1 && !jsonFieldFormat.contains("'T'")) {
jsonFieldFormat = jsonFieldFormat.replaceAll("T", "'T'");
jsonFieldFormat = jsonFieldFormat.replace("T", "'T'");
}
if (!jsonFieldFormat.isEmpty()) {

View File

@ -492,7 +492,7 @@ public class ObjectWriterCreator {
} 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 @@ public class ObjectWriterCreator {
SUPER,
superType,
objectClass.getSuperclass(),
o -> o
Function.identity()
);
fieldWriters.add(superWriter);
}

View File

@ -355,7 +355,7 @@ public class ObjectWriterCreatorASM
} 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);
}
}

View File

@ -40,7 +40,7 @@ final class ObjectWriterImplDouble
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);
}
}

View File

@ -394,14 +394,11 @@ public class ObjectWriterProvider
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;
}
}

View File

@ -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());
}
}

View File

@ -82,7 +82,7 @@ public class UUIDTest {
uuid,
JSONReader.ofJSONB(
JSONB.toBytes(
str.replaceAll("-", "")
str.replace("-", "")
)
).readUUID()
);

View File

@ -17,7 +17,7 @@ public class UUIDTest3 {
};
static String toString(UUID id) {
return id.toString().replaceAll("-", "");
return id.toString().replace("-", "");
}
@Test

View File

@ -12,9 +12,9 @@ public class Int2Decoder {
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);
}
}
}

View File

@ -24,8 +24,7 @@ public class TestController {
@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) {

View File

@ -73,7 +73,7 @@ public class FastJson2Provider
* Can serialize/deserialize all types.
*/
public FastJson2Provider() {
this((Class<?>[]) null);
this(null);
}
/**

View File

@ -81,7 +81,7 @@ public class Fastjson2ActionExecutor
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 pathqueryString?
return super.changeValue(ctx, p, pi, pt, bodyObj);
}
@ -93,7 +93,7 @@ public class Fastjson2ActionExecutor
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
//

View File

@ -28,11 +28,7 @@ public class GeoJsonPointReader
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();

View File

@ -33,11 +33,7 @@ public class GeoJsonPolygonReader
List<Point> points = new ArrayList<>();
for (; ; ) {
if (jsonReader.nextIfObjectEnd()) {
break;
}
while (!jsonReader.nextIfObjectEnd()) {
long nameHashCode = jsonReader.readFieldNameHashCode();
if (nameHashCode == HASH_TYPE) {
long valueHashCode = jsonReader.readValueHashCode();

View File

@ -81,7 +81,7 @@ public class Fastjson2Encoder
}
private void configFilter(JSONWriter.Context context, Filter... filters) {
if (filters == null || filters.length == 0) {
if (filters == null) {
return;
}
for (Filter filter : filters) {

View File

@ -11,9 +11,7 @@ import javax.servlet.ServletOutputStream;
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 class FastJsonJsonView
* @return the object to be rendered
*/
protected Object filterModel(Map<String, Object> model) {
Map<String, Object> result = new HashMap<String, Object>(model.size());
Set<String> renderedAttributes = !CollectionUtils.isEmpty(this.renderedAttributes) ? //
this.renderedAttributes //
: model.keySet();
int expectSize = model.size();
final Set<String> 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<String, Object> result = new HashMap<>(expectSize, 1F);
for (Map.Entry<String, Object> 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<String, Object> entry : result.entrySet()) {
return entry.getValue();
}
if (extractValueFromSingleKeyModel && result.size() == 1) {
for (Map.Entry<String, Object> entry : result.entrySet()) {
return entry.getValue();
}
}
return result;
}
@Override
protected void setResponseContentType(HttpServletRequest request, HttpServletResponse response) {
super.setResponseContentType(request, response);
}
}

View File

@ -72,7 +72,7 @@ public class AwtRederModule
public Color apply(Map<Long, Object> 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);

View File

@ -11,6 +11,7 @@ import org.apache.arrow.vector.types.pojo.Field;
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 class ArrowByteArrayConsumer
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 class ArrowByteArrayConsumer
((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 class ArrowByteArrayConsumer
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 class ArrowByteArrayConsumer
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;

View File

@ -10,6 +10,7 @@ import org.apache.arrow.vector.*;
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 class ArrowUtils {
}
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 class ArrowUtils {
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 class ArrowUtils {
}
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 class ArrowUtils {
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 class ArrowUtils {
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 class ArrowUtils {
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 class ArrowUtils {
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 class ArrowUtils {
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) {

View File

@ -22,7 +22,7 @@ public class CSVUtils {
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 class CSVUtils {
sql.append('\t');
if (special) {
sql.append("COL_" + i);
sql.append("COL_").append(i);
} else {
sql.append(columnName);
}

View File

@ -13,7 +13,7 @@ public class Feature
extends Geometry {
private String id;
private Geometry geometry;
private Map<String, String> properties = new LinkedHashMap<String, String>();
private Map<String, String> properties = new LinkedHashMap<>();
public Feature() {
super("Feature");
}

View File

@ -11,7 +11,7 @@ import java.util.List;
@JSONType(typeName = "FeatureCollection", orders = {"type", "bbox", "coordinates"})
public class FeatureCollection
extends Geometry {
private List<Feature> features = new ArrayList<Feature>();
private List<Feature> features = new ArrayList<>();
public FeatureCollection() {
super("FeatureCollection");
}

View File

@ -11,7 +11,7 @@ import java.util.List;
@JSONType(typeName = "GeometryCollection", orders = {"type", "bbox", "geometries"})
public class GeometryCollection
extends Geometry {
private List<Geometry> geometries = new ArrayList<Geometry>();
private List<Geometry> geometries = new ArrayList<>();
public GeometryCollection() {
super("GeometryCollection");
}

View File

@ -99,7 +99,7 @@ public class JSONBCodec
}
}
static final class JSONBDecoder
protected static final class JSONBDecoder
implements Decoder<Object> {
final JSONReader.Context context;
final Type valueType;

View File

@ -52,7 +52,7 @@ public class Retrofit2ConverterFactory
Annotation[] annotations,
Retrofit retrofit
) {
return new ResponseBodyConverter<Object>(type);
return new ResponseBodyConverter<>(type);
}
@Override
@ -62,7 +62,7 @@ public class Retrofit2ConverterFactory
Annotation[] methodAnnotations,
Retrofit retrofit
) {
return new RequestBodyConverter<Object>();
return new RequestBodyConverter<>();
}
public FastJsonConfig getFastJsonConfig() {

View File

@ -9,7 +9,6 @@ import com.alibaba.fastjson.util.TypeUtils;
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 abstract class JSON
}
}
@SuppressWarnings("unchecked")
public static <T> T parseObject(String str, TypeReference<T> 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> 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> T parseObject(String str, Class<T> objectClass) {
@ -723,7 +721,7 @@ public abstract class JSON
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> T parseObject(
@ -763,7 +761,7 @@ public abstract class JSON
/**
* @since 2.0.7
*/
public static <T> 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 abstract class JSON
try {
JSONReader jsonReader = JSONReader.of(jsonBytes, context);
if (filter instanceof Filter) {
context.config((Filter) filter);
if (filter != null) {
context.config(filter);
}
ObjectReader<T> objectReader = jsonReader.getObjectReader(type);
@ -1134,7 +1132,6 @@ public abstract class JSON
}
}
@SuppressWarnings("unchecked")
public static <T> T parseObject(
byte[] input,
int off,
@ -1608,7 +1605,7 @@ public abstract class JSON
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 abstract class JSON
}
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 abstract class JSON
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 abstract class JSON
public static <T> T toJavaObject(JSON json, Class<T> clazz) {
if (json instanceof JSONObject) {
return ((JSONObject) json).toJavaObject(clazz);
return json.toJavaObject(clazz);
}
String str = toJSONString(json);

View File

@ -192,12 +192,12 @@ public class JSONArray
}
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 class JSONArray
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 class JSONArray
}
public <T> List<T> toJavaList(Class<T> clazz) {
List<T> list = new ArrayList<T>(this.size());
List<T> list = new ArrayList<>(this.size());
ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider();
ObjectReader objectReader = provider.getObjectReader(clazz);
@ -877,10 +877,8 @@ public class JSONArray
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);
}

View File

@ -78,9 +78,9 @@ public class JSONObject
public JSONObject(int initialCapacity, boolean ordered) {
if (ordered) {
map = new LinkedHashMap<String, Object>(initialCapacity);
map = new LinkedHashMap<>(initialCapacity);
} else {
map = new HashMap<String, Object>(initialCapacity);
map = new HashMap<>(initialCapacity);
}
}
@ -425,7 +425,7 @@ public class JSONObject
return false;
}
return booleanVal.booleanValue();
return booleanVal;
}
public byte getByteValue(String key) {
@ -751,12 +751,12 @@ public class JSONObject
}
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 class JSONObject
}
@Override
public void putAll(Map<? extends String, ? extends Object> m) {
public void putAll(Map<? extends String, ?> m) {
map.putAll(m);
}
public JSONObject fluentPutAll(Map<? extends String, ? extends Object> m) {
public JSONObject fluentPutAll(Map<? extends String, ?> m) {
map.putAll(m);
return this;
}
@ -903,8 +903,8 @@ public class JSONObject
@Override
public Object clone() {
return new JSONObject(map instanceof LinkedHashMap //
? new LinkedHashMap<String, Object>(map) //
: new HashMap<String, Object>(map)
? new LinkedHashMap<>(map) //
: new HashMap<>(map)
);
}

View File

@ -5,7 +5,7 @@ import java.util.List;
public class JSONPObject
extends com.alibaba.fastjson2.JSONPObject {
private final List<Object> parameters = new ArrayList<Object>();
private final List<Object> parameters = new ArrayList<>();
public JSONPObject() {
}

View File

@ -51,21 +51,20 @@ public class JSONPath {
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 class JSONPath {
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) {

View File

@ -27,7 +27,7 @@ import java.util.concurrent.ConcurrentMap;
*/
public class TypeReference<T> {
static ConcurrentMap<Type, Type> classTypeCache
= new ConcurrentHashMap<Type, Type>(16, 0.75f, 1);
= new ConcurrentHashMap<>(16, 0.75f, 1);
protected final Type type;

View File

@ -17,6 +17,7 @@ import java.io.*;
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 class FastJsonProvider
if (serializerFeatures == null) {
serializerFeatures = new SerializerFeature[]{SerializerFeature.PrettyFormat};
} else {
List<SerializerFeature> featureList = new ArrayList<SerializerFeature>(Arrays.asList(serializerFeatures));
List<SerializerFeature> featureList = new ArrayList<>(Arrays.asList(serializerFeatures));
featureList.add(SerializerFeature.PrettyFormat);
serializerFeatures = featureList.toArray(serializerFeatures);
}
@ -397,10 +398,8 @@ public class FastJsonProvider
}
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 @@ public class FastJsonProvider
writer.writeAny(object);
int len = writer.flushTo(os, charset);
return len;
} finally {
writer.close();
return writer.flushTo(os, charset);
}
}

View File

@ -17,6 +17,7 @@ import javax.servlet.http.HttpServletResponse;
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 class FastJsonJsonView
* @return the object to be rendered
*/
protected Object filterModel(Map<String, Object> model) {
Map<String, Object> result = new HashMap<String, Object>(model.size());
Map<String, Object> result = new HashMap<>(model.size());
Set<String> renderedAttributes = !CollectionUtils.isEmpty(this.renderedAttributes) ? //
this.renderedAttributes //
: model.keySet();

View File

@ -12,7 +12,7 @@ import java.util.List;
* @author liuming
*/
public class PropertyPreFilters {
private List<MySimplePropertyPreFilter> filters = new ArrayList<MySimplePropertyPreFilter>();
private List<MySimplePropertyPreFilter> filters = new ArrayList<>();
public MySimplePropertyPreFilter addFilter() {
MySimplePropertyPreFilter filter = new MySimplePropertyPreFilter();

View File

@ -163,7 +163,7 @@ public class FastJsonView
* @return the object to be rendered
*/
protected Object filterModel(Map<String, Object> model) {
Map<String, Object> result = new HashMap<String, Object>(model.size());
Map<String, Object> result = new HashMap<>(model.size());
Set<String> renderedAttributes = !CollectionUtils.isEmpty(this.renderedAttributes) ? //
this.renderedAttributes //
: model.keySet();

View File

@ -110,11 +110,11 @@ public class 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 class FieldInfo
}
private static boolean getArgument(Type[] typeArgs, Map<TypeVariable, Type> genericInfo) {
if (genericInfo == null || genericInfo.size() == 0) {
if (genericInfo == null || genericInfo.isEmpty()) {
return false;
}
boolean changed = false;
@ -305,8 +305,9 @@ public class FieldInfo
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;
}
}

View File

@ -35,8 +35,6 @@ import java.math.BigDecimal;
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<Class, String[]> kotlinIgnores;
private static volatile boolean kotlinIgnores_error;
private static ConcurrentMap<String, Class<?>> mappings = new ConcurrentHashMap<String, Class<?>>(256, 0.75f, 1);
private static Class<?> pathClass;
private static boolean PATH_CLASS_ERROR;
private static boolean transientClassInited;
private static Class<? extends Annotation> transientClass;
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T> T cast(Object obj, Class<T> clazz, ParserConfig config) {
return com.alibaba.fastjson2.util.TypeUtils.cast(obj, clazz, config.getProvider());
}
@ -102,72 +96,42 @@ public class TypeUtils {
@SuppressWarnings({"rawtypes", "unchecked"})
public static <T> 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<T>) itemType, mapping, 0);
} else {
itemValue = cast(item, (Class<T>) 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<T>) itemType, mapping, 0);
} else {
itemValue = cast(item, (Class<T>) 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 class TypeUtils {
}
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 class TypeUtils {
// 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 <T> 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<T>) itemType, mapping, 0);
} else {
itemValue = cast(item, (Class<T>) itemType, mapping);
}
} else {
itemValue = cast(item, itemType, mapping);
}
to.add(itemValue);
}
}
@SuppressWarnings("unchecked")
public static <T> T castToJavaBean(Map<String, Object> map, Class<T> clazz, ParserConfig config) {
try {
@ -297,8 +279,8 @@ public class TypeUtils {
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 class TypeUtils {
}
public static <A extends Annotation> A getAnnotation(Class<?> targetClass, Class<A> 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 extends Annotation> A getAnnotationOrCandidate(Class<?> clazz, Class<A> 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 extends Annotation> A getAnnotation(Field field, Class<A> 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 class TypeUtils {
if (mixInField == null) {
return targetAnnotation;
}
mixInAnnotation = mixInField.getAnnotation(annotationClass);
A mixInAnnotation = mixInField.getAnnotation(annotationClass);
if (mixInAnnotation != null) {
return mixInAnnotation;
}
@ -535,16 +501,17 @@ public class TypeUtils {
return targetAnnotation;
}
public static <A extends Annotation> A getAnnotation(Method method, Class<A> 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 extends Annotation> A getAnnotation(Method method, Class<A> annotationClass) {
Class<?> mixInClass = getMixInClass(method.getDeclaringClass());
if (mixInClass != null) {
Method mixInMethod = null;
@ -559,15 +526,14 @@ public class TypeUtils {
// 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 class TypeUtils {
public static List<FieldInfo> computeGetters(Class<?> clazz, Map<String, String> aliasMap, boolean sorted) {
JSONType jsonType = TypeUtils.getAnnotation(clazz, JSONType.class);
Map<String, Field> fieldCacheMap = new HashMap<String, Field>();
Map<String, Field> fieldCacheMap = new HashMap<>();
ParserConfig.parserAllFieldToCache(clazz, fieldCacheMap);
return computeGetters(clazz, jsonType, aliasMap, fieldCacheMap, sorted, PropertyNamingStrategy.CamelCase);
}
@ -727,7 +693,7 @@ public class TypeUtils {
boolean sorted, //
PropertyNamingStrategy propertyNamingStrategy //
) {
Map<String, FieldInfo> fieldInfoMap = new LinkedHashMap<String, FieldInfo>();
Map<String, FieldInfo> fieldInfoMap = new LinkedHashMap<>();
boolean kotlin = TypeUtils.isKotlin(clazz);
// for kotlin
Constructor[] constructors = null;
@ -776,10 +742,10 @@ public class TypeUtils {
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 @@ public class TypeUtils {
}
private static List<FieldInfo> getFieldInfos(Class<?> clazz, boolean sorted, Map<String, FieldInfo> fieldInfoMap) {
List<FieldInfo> fieldInfoList = new ArrayList<FieldInfo>();
List<FieldInfo> 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<String, FieldInfo> map = new LinkedHashMap<String, FieldInfo>(fieldInfoMap.size());
LinkedHashMap<String, FieldInfo> map = new LinkedHashMap<>(fieldInfoMap.size());
for (FieldInfo field : fieldInfoMap.values()) {
map.put(field.name, field);
}
@ -1178,8 +1144,8 @@ public class TypeUtils {
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 class TypeUtils {
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 class TypeUtils {
static boolean isKotlinIgnore(Class clazz, String methodName) {
if (kotlinIgnores == null && !kotlinIgnores_error) {
try {
Map<Class, String[]> map = new HashMap<Class, String[]>();
Map<Class, String[]> 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 class TypeUtils {
}
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<Class<?>> enclosingClasses = new ArrayList<Class<?>>(2);
List<Class<?>> enclosingClasses = new ArrayList<>(2);
for (Class<?> enclosingClass = mixInClass.getEnclosingClass(); enclosingClass != null; enclosingClass = enclosingClass.getEnclosingClass()) {
enclosingClasses.add(enclosingClass);
}
@ -1454,15 +1414,15 @@ public class TypeUtils {
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