Merge pull request #515 from CodePlayer/master

优化部分代码实现细节
This commit is contained in:
wenshao
2016-03-11 11:20:41 +08:00
10 changed files with 158 additions and 144 deletions
+4 -1
View File
@@ -95,6 +95,9 @@ public abstract class JSON implements JSONStreamAware, JSONAware {
// com.alibaba.fastjson.serializer.SerializerFeature.WriteSlashAsSpecial.getMask();
DEFAULT_GENERATE_FEATURE = features;
}
/** 长度为 0 的 SerializeFilter 数组 */
public static final SerializeFilter[] EMPTY_SERIALIZE_FILTERS = new SerializeFilter[0];
public static Object parse(String text) {
return parse(text, DEFAULT_PARSER_FEATURE);
@@ -379,7 +382,7 @@ public abstract class JSON implements JSONStreamAware, JSONAware {
// ======================
public static String toJSONString(Object object) {
return toJSONString(object, new SerializerFeature[0]);
return toJSONString(object, EMPTY_SERIALIZE_FILTERS);
}
public static String toJSONString(Object object, SerializerFeature... features) {
@@ -167,7 +167,7 @@ public class JSONObject extends JSON implements Map<String, Object>, Cloneable,
return 0;
}
return castToByte(value).byteValue();
return castToByte(value).byteValue(); // TODO 如果 value 是""、"null"或"NULL",可能会存在报空指针的情况,是否需要加以处理? 其他转换也存在类似情况
}
public Short getShort(String key) {
@@ -826,7 +826,7 @@ public class JSONPath implements ObjectSerializer {
throw new JSONPathException("illeal jsonpath syntax. " + path);
}
StringBuffer buf = new StringBuffer();
StringBuilder buf = new StringBuilder();
while (!isEOF()) {
if (ch == '\\') {
next();
@@ -108,7 +108,7 @@ public class JavaBeanDeserializer implements ObjectDeserializer {
Object object;
try {
Constructor<?> constructor = beanInfo.getDefaultConstructor();
if (constructor.getParameterTypes().length == 0) {
if (constructor.getParameterCount() == 0) {
object = constructor.newInstance();
} else {
object = constructor.newInstance(parser.getContext().getObject());
@@ -219,7 +219,7 @@ public class JavaBeanDeserializer implements ObjectDeserializer {
}
if (lexer.token() != JSONToken.LBRACE && lexer.token() != JSONToken.COMMA) {
StringBuffer buf = (new StringBuffer()) //
StringBuilder buf = new StringBuilder(72) // 单线程换StringBuilder,并设置初始化容量,避免内部逐步扩容开销
.append("syntax error, expect {, actual ") //
.append(lexer.tokenName()) //
.append(", pos ") //
@@ -127,18 +127,19 @@ public class ThrowableDeserializer extends JavaBeanDeserializer {
Constructor<?> messageConstructor = null;
Constructor<?> causeConstructor = null;
for (Constructor<?> constructor : exClass.getConstructors()) {
if (constructor.getParameterTypes().length == 0) {
if (constructor.getParameterCount() == 0) {
defaultConstructor = constructor;
continue;
}
if (constructor.getParameterTypes().length == 1 && constructor.getParameterTypes()[0] == String.class) {
if (constructor.getParameterCount() == 1 && constructor.getParameterTypes()[0] == String.class) {
messageConstructor = constructor;
continue;
}
if (constructor.getParameterTypes().length == 2 && constructor.getParameterTypes()[0] == String.class
&& constructor.getParameterTypes()[1] == Throwable.class) {
Class<?>[] types;
if (constructor.getParameterCount() == 2 && (types = constructor.getParameterTypes())[0] == String.class
&& types[1] == Throwable.class) {
causeConstructor = constructor;
continue;
}
@@ -50,6 +50,7 @@ public abstract class FieldSerializer {
for (SerializerFeature feature : annotation.serialzeFeatures()) {
if (feature == SerializerFeature.WriteMapNullValue) {
writeNull = true;
break;
}
}
}
@@ -33,13 +33,13 @@ public class ASMUtils {
}
public static String getDesc(Method method) {
StringBuffer buf = new StringBuffer();
buf.append("(");
java.lang.Class<?>[] types = method.getParameterTypes();
Class<?>[] types = method.getParameterTypes();
StringBuilder buf = new StringBuilder((types.length + 1) << 4);
buf.append('(');
for (int i = 0; i < types.length; ++i) {
buf.append(getDesc(types[i]));
}
buf.append(")");
buf.append(')');
buf.append(getDesc(method.getReturnType()));
return buf.toString();
}
@@ -60,7 +60,7 @@ public class ASMUtils {
} else {
if (!parameterType.isPrimitive()) {
String clsName = parameterType.getName();
return clsName.replaceAll("\\.", "/");
return clsName.replace('.', '/'); // 直接基于字符串替换,不使用正则替换
} else {
return getPrimitiveLetter(parameterType);
}
@@ -133,72 +133,73 @@ public class DeserializeBeanInfo {
Class<?> builderClass = beanInfo.getBuilderClass();
Constructor<?> defaultConstructor = getDefaultConstructor(builderClass == null ? clazz : builderClass);
if (defaultConstructor != null) {
if (defaultConstructor != null) { // 如果存在默认构造方法
TypeUtils.setAccessible(defaultConstructor);
beanInfo.setDefaultConstructor(defaultConstructor);
} else if (defaultConstructor == null && !(clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers()))) {
Constructor<?> creatorConstructor = getCreatorConstructor(clazz);
if (creatorConstructor != null) {
if (creatorConstructor != null) { // 基于标记 JSONCreator 注解的构造方法
TypeUtils.setAccessible(creatorConstructor);
beanInfo.setCreatorConstructor(creatorConstructor);
for (int i = 0; i < creatorConstructor.getParameterTypes().length; ++i) {
Annotation[] paramAnnotations = creatorConstructor.getParameterAnnotations()[i];
JSONField fieldAnnotation = null;
for (Annotation paramAnnotation : paramAnnotations) {
if (paramAnnotation instanceof JSONField) {
fieldAnnotation = (JSONField) paramAnnotation;
break;
}
}
if (fieldAnnotation == null) {
throw new JSONException("illegal json creator");
}
Class<?> fieldClass = creatorConstructor.getParameterTypes()[i];
Type fieldType = creatorConstructor.getGenericParameterTypes()[i];
Field field = TypeUtils.getField(clazz, fieldAnnotation.name());
final int ordinal = fieldAnnotation.ordinal();
final int serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures());
FieldInfo fieldInfo = new FieldInfo(fieldAnnotation.name(), clazz, fieldClass, fieldType, field,
ordinal, serialzeFeatures);
beanInfo.add(fieldInfo);
}
int count = creatorConstructor.getParameterCount();
if (count > 0) {
Annotation[][] paramAnnotationArrays = creatorConstructor.getParameterAnnotations();
for (int i = 0; i < count; ++i) {
Annotation[] paramAnnotations = paramAnnotationArrays[i];
JSONField fieldAnnotation = null;
for (Annotation paramAnnotation : paramAnnotations) {
if (paramAnnotation instanceof JSONField) {
fieldAnnotation = (JSONField) paramAnnotation;
break;
}
}
if (fieldAnnotation == null) {
throw new JSONException("illegal json creator");
}
Class<?> fieldClass = creatorConstructor.getParameterTypes()[i];
Type fieldType = creatorConstructor.getGenericParameterTypes()[i];
Field field = TypeUtils.getField(clazz, fieldAnnotation.name());
final int ordinal = fieldAnnotation.ordinal();
final int serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures());
FieldInfo fieldInfo = new FieldInfo(fieldAnnotation.name(), clazz, fieldClass, fieldType, field,
ordinal, serialzeFeatures);
beanInfo.add(fieldInfo);
}
}
return beanInfo;
}
Method factoryMethod = getFactoryMethod(clazz);
Method factoryMethod = getFactoryMethod(clazz); // 基于标记 JSONCreator 注解的工厂方法
if (factoryMethod != null) {
TypeUtils.setAccessible(factoryMethod);
beanInfo.setFactoryMethod(factoryMethod);
for (int i = 0; i < factoryMethod.getParameterTypes().length; ++i) {
Annotation[] paramAnnotations = factoryMethod.getParameterAnnotations()[i];
JSONField fieldAnnotation = null;
for (Annotation paramAnnotation : paramAnnotations) {
if (paramAnnotation instanceof JSONField) {
fieldAnnotation = (JSONField) paramAnnotation;
break;
int count = factoryMethod.getParameterCount();
if (count > 0) {
Annotation[][] paramAnnotationArrays = factoryMethod.getParameterAnnotations();
for (int i = 0; i < count; ++i) {
Annotation[] paramAnnotations = paramAnnotationArrays[i];
JSONField fieldAnnotation = null;
for (Annotation paramAnnotation : paramAnnotations) {
if (paramAnnotation instanceof JSONField) {
fieldAnnotation = (JSONField) paramAnnotation;
break;
}
}
if (fieldAnnotation == null) {
throw new JSONException("illegal json creator");
}
}
if (fieldAnnotation == null) {
throw new JSONException("illegal json creator");
}
Class<?> fieldClass = factoryMethod.getParameterTypes()[i];
Type fieldType = factoryMethod.getGenericParameterTypes()[i];
Field field = TypeUtils.getField(clazz, fieldAnnotation.name());
final int ordinal = fieldAnnotation.ordinal();
final int serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures());
FieldInfo fieldInfo = new FieldInfo(fieldAnnotation.name() //
, clazz //
, fieldClass //
, fieldType //
, field //
, ordinal //
, serialzeFeatures);
beanInfo.add(fieldInfo);
}
Class<?> fieldClass = factoryMethod.getParameterTypes()[i];
Type fieldType = factoryMethod.getGenericParameterTypes()[i];
Field field = TypeUtils.getField(clazz, fieldAnnotation.name());
final int ordinal = fieldAnnotation.ordinal();
final int serialzeFeatures = SerializerFeature.of(fieldAnnotation.serialzeFeatures());
FieldInfo fieldInfo = new FieldInfo(fieldAnnotation.name(), clazz, fieldClass, fieldType, field, ordinal, serialzeFeatures);
beanInfo.add(fieldInfo);
}
}
return beanInfo;
}
@@ -244,8 +245,7 @@ public class DeserializeBeanInfo {
if (annotation.name().length() != 0) {
String propertyName = annotation.name();
beanInfo.add(new FieldInfo(propertyName, method, null, clazz, type, ordinal, serialzeFeatures));
TypeUtils.setAccessible(method);
beanInfo.add(new FieldInfo(propertyName, method, null, clazz, type, ordinal, serialzeFeatures));
continue;
}
}
@@ -270,8 +270,7 @@ public class DeserializeBeanInfo {
String propertyName = properNameBuilder.toString();
beanInfo.add(new FieldInfo(propertyName, method, null, clazz, type, ordinal, serialzeFeatures));
TypeUtils.setAccessible(method);
beanInfo.add(new FieldInfo(propertyName, method, null, clazz, type, ordinal, serialzeFeatures));
}
if (builderClass != null) {
@@ -314,7 +313,7 @@ public class DeserializeBeanInfo {
}
}
for (Method method : clazz.getMethods()) {
for (Method method : clazz.getMethods()) { //
int ordinal = 0, serialzeFeatures = 0;
String methodName = method.getName();
if (methodName.length() < 4) {
@@ -330,7 +329,7 @@ public class DeserializeBeanInfo {
continue;
}
if (method.getParameterTypes().length != 1) {
if (method.getParameterCount() != 1) {
continue;
}
@@ -351,12 +350,11 @@ public class DeserializeBeanInfo {
if (annotation.name().length() != 0) {
String propertyName = annotation.name();
beanInfo.add(new FieldInfo(propertyName, method, null, clazz, type, ordinal, serialzeFeatures));
TypeUtils.setAccessible(method);
continue;
}
}
if (!methodName.startsWith("set")) {
if (!methodName.startsWith("set")) { // TODO "set"的判断放在 JSONField 注解后面,意思是允许非 setter 方法标记 JSONField 注解?
continue;
}
@@ -396,8 +394,7 @@ public class DeserializeBeanInfo {
if (fieldAnnotation.name().length() != 0) {
propertyName = fieldAnnotation.name();
beanInfo.add(new FieldInfo(propertyName, method, field, clazz, type, ordinal,
serialzeFeatures));
beanInfo.add(new FieldInfo(propertyName, method, field, clazz, type, ordinal, serialzeFeatures));
continue;
}
}
@@ -405,10 +402,9 @@ public class DeserializeBeanInfo {
}
beanInfo.add(new FieldInfo(propertyName, method, null, clazz, type, ordinal, serialzeFeatures));
TypeUtils.setAccessible(method);
}
for (Field field : clazz.getFields()) {
for (Field field : clazz.getFields()) { // public static fields
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
@@ -417,7 +413,7 @@ public class DeserializeBeanInfo {
for (FieldInfo item : beanInfo.getFieldList()) {
if (item.getName().equals(field.getName())) {
contains = true;
continue;
break; // 已经是 contains = true,无需继续遍历
}
}
@@ -441,7 +437,7 @@ public class DeserializeBeanInfo {
beanInfo.add(new FieldInfo(propertyName, null, field, clazz, type, ordinal, serialzeFeatures));
}
for (Method method : clazz.getMethods()) {
for (Method method : clazz.getMethods()) { // getter methods
String methodName = method.getName();
if (methodName.length() < 4) {
continue;
@@ -452,7 +448,7 @@ public class DeserializeBeanInfo {
}
if (methodName.startsWith("get") && Character.isUpperCase(methodName.charAt(3))) {
if (method.getParameterTypes().length != 0) {
if (method.getParameterCount() != 0) {
continue;
}
@@ -477,7 +473,6 @@ public class DeserializeBeanInfo {
}
beanInfo.add(new FieldInfo(propertyName, method, null, clazz, type));
TypeUtils.setAccessible(method);
}
}
}
@@ -491,8 +486,10 @@ public class DeserializeBeanInfo {
}
Constructor<?> defaultConstructor = null;
for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
if (constructor.getParameterTypes().length == 0) {
final Constructor<?>[] constructors = clazz.getDeclaredConstructors();
for (Constructor<?> constructor : constructors) {
if (constructor.getParameterCount() == 0) { // getParameterTypes() 内部是调用数组的克隆方法,开销相对较大
defaultConstructor = constructor;
break;
}
@@ -500,9 +497,9 @@ public class DeserializeBeanInfo {
if (defaultConstructor == null) {
if (clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers())) {
for (Constructor<?> constructor : clazz.getDeclaredConstructors()) {
if (constructor.getParameterTypes().length == 1
&& constructor.getParameterTypes()[0].equals(clazz.getDeclaringClass())) {
for (Constructor<?> constructor : constructors) {
if (constructor.getParameterCount() == 1
&& constructor.getParameterTypes()[0].equals(clazz.getDeclaringClass())) {
defaultConstructor = constructor;
break;
}
@@ -520,11 +517,11 @@ public class DeserializeBeanInfo {
JSONCreator annotation = constructor.getAnnotation(JSONCreator.class);
if (annotation != null) {
if (creatorConstructor != null) {
throw new JSONException("multi-json creator");
throw new JSONException("multi-JSONCreator");
}
creatorConstructor = constructor;
break;
// 不应该break,否则多个构造方法上存在 JSONCreator 注解时,并不会触发上述异常抛出
}
}
return creatorConstructor;
@@ -545,11 +542,11 @@ public class DeserializeBeanInfo {
JSONCreator annotation = method.getAnnotation(JSONCreator.class);
if (annotation != null) {
if (factoryMethod != null) {
throw new JSONException("multi-json creator");
throw new JSONException("multi-JSONCreator");
}
factoryMethod = method;
break;
// 不应该break,否则多个静态工厂方法上存在 JSONCreator 注解时,并不会触发上述异常抛出
}
}
return factoryMethod;
@@ -84,7 +84,7 @@ public class FieldInfo implements Comparable<FieldInfo> {
Type fieldType;
Class<?> fieldClass;
if (method != null) {
if (method.getParameterTypes().length == 1) {
if (method.getParameterCount() == 1) {
fieldClass = method.getParameterTypes()[0];
fieldType = method.getGenericParameterTypes()[0];
} else {
@@ -128,7 +128,7 @@ public class FieldInfo implements Comparable<FieldInfo> {
return label;
}
public static Type getFieldType(Class<?> clazz, Type type, Type fieldType) {
public static Type getFieldType(final Class<?> clazz, final Type type, Type fieldType) {
if (clazz == null || type == null) {
return fieldType;
}
@@ -152,10 +152,11 @@ public class FieldInfo implements Comparable<FieldInfo> {
if (fieldType instanceof TypeVariable) {
ParameterizedType paramType = (ParameterizedType) TypeUtils.getGenericParamType(type);
Class<?> parameterizedClass = TypeUtils.getClass(paramType);
TypeVariable<?> typeVar = (TypeVariable<?>) fieldType;
for (int i = 0; i < parameterizedClass.getTypeParameters().length; ++i) {
if (parameterizedClass.getTypeParameters()[i].getName().equals(typeVar.getName())) {
final TypeVariable<?> typeVar = (TypeVariable<?>) fieldType;
TypeVariable<?>[] typeVariables = parameterizedClass.getTypeParameters();
for (int i = 0; i < typeVariables.length; ++i) {
if (typeVariables[i].getName().equals(typeVar.getName())) {
fieldType = paramType.getActualTypeArguments()[i];
return fieldType;
}
@@ -167,16 +168,23 @@ public class FieldInfo implements Comparable<FieldInfo> {
Type[] arguments = parameterizedFieldType.getActualTypeArguments();
boolean changed = false;
TypeVariable<?>[] typeVariables = null;
Type[] actualTypes = null;
for (int i = 0; i < arguments.length; ++i) {
Type feildTypeArguement = arguments[i];
if (feildTypeArguement instanceof TypeVariable) {
TypeVariable<?> typeVar = (TypeVariable<?>) feildTypeArguement;
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
for (int j = 0; j < clazz.getTypeParameters().length; ++j) {
if (clazz.getTypeParameters()[j].getName().equals(typeVar.getName())) {
arguments[i] = parameterizedType.getActualTypeArguments()[j];
if (typeVariables == null) {
typeVariables = clazz.getTypeParameters();
}
for (int j = 0; j < typeVariables.length; ++j) {
if (typeVariables[j].getName().equals(typeVar.getName())) {
if (actualTypes == null) {
actualTypes = ((ParameterizedType) type).getActualTypeArguments();
}
arguments[i] = actualTypes[j];
changed = true;
}
}
@@ -140,13 +140,13 @@ public class TypeUtils {
}
if (strVal.length() != 1) {
throw new JSONException("can not cast to byte, value : " + value);
throw new JSONException("can not cast to char, value : " + value);
}
return strVal.charAt(0);
}
throw new JSONException("can not cast to byte, value : " + value);
throw new JSONException("can not cast to char, value : " + value);
}
public static Short castToShort(Object value) {
@@ -271,15 +271,15 @@ public class TypeUtils {
if (value == null) {
return null;
}
if (value instanceof Date) { // 使用频率最高的,应优先处理
return (Date) value;
}
if (value instanceof Calendar) {
return ((Calendar) value).getTime();
}
if (value instanceof Date) {
return (Date) value;
}
long longValue = -1;
if (value instanceof Number) {
@@ -369,19 +369,19 @@ public class TypeUtils {
if (value == null) {
return null;
}
if (value instanceof java.sql.Date) {
return (java.sql.Date) value;
}
if (value instanceof java.util.Date) {
return new java.sql.Date(((java.util.Date) value).getTime());
}
if (value instanceof Calendar) {
return new java.sql.Date(((Calendar) value).getTimeInMillis());
}
if (value instanceof java.sql.Date) {
return (java.sql.Date) value;
}
if (value instanceof java.util.Date) {
return new java.sql.Date(((java.util.Date) value).getTime());
}
long longValue = 0;
if (value instanceof Number) {
@@ -398,7 +398,7 @@ public class TypeUtils {
}
if (longValue <= 0) {
throw new JSONException("can not cast to Date, value : " + value);
throw new JSONException("can not cast to Date, value : " + value); // TODO 忽略 1970-01-01 之前的时间处理?
}
return new java.sql.Date(longValue);
@@ -503,10 +503,6 @@ public class TypeUtils {
return null;
}
if ("null".equals(strVal)) {
return null;
}
if ("null".equals(strVal) || "NULL".equals(strVal)) {
return null;
}
@@ -1314,36 +1310,44 @@ public class TypeUtils {
return fieldInfoList;
}
public static JSONField getSupperMethodAnnotation(Class<?> clazz, Method method) {
for (Class<?> interfaceClass : clazz.getInterfaces()) {
for (Method interfaceMethod : interfaceClass.getMethods()) {
if (!interfaceMethod.getName().equals(method.getName())) {
continue;
}
public static JSONField getSupperMethodAnnotation(final Class<?> clazz, final Method method) {
Class<?>[] interfaces = clazz.getInterfaces();
if (interfaces.length > 0) {
int paramsCount = method.getParameterCount();
Class<?>[] methodParamTypes = null;
for (Class<?> interfaceClass : interfaces) {
for (Method interfaceMethod : interfaceClass.getMethods()) {
if (interfaceMethod.getParameterCount() != paramsCount) {
continue;
}
if (!interfaceMethod.getName().equals(method.getName())) {
continue;
}
boolean match = true;
if (paramsCount > 0) {
Class<?>[] interfaceTypes = interfaceMethod.getParameterTypes();
if (methodParamTypes == null) {
methodParamTypes = method.getParameterTypes();
}
for (int i = 0; i < paramsCount; ++i) {
if (!interfaceTypes[i].equals(methodParamTypes[i])) {
match = false;
break;
}
}
}
if (interfaceMethod.getParameterTypes().length != method.getParameterTypes().length) {
continue;
}
if (!match) {
continue;
}
boolean match = true;
for (int i = 0; i < interfaceMethod.getParameterTypes().length; ++i) {
if (!interfaceMethod.getParameterTypes()[i].equals(method.getParameterTypes()[i])) {
match = false;
break;
JSONField annotation = interfaceMethod.getAnnotation(JSONField.class);
if (annotation != null) {
return annotation;
}
}
if (!match) {
continue;
}
JSONField annotation = interfaceMethod.getAnnotation(JSONField.class);
if (annotation != null) {
return annotation;
}
}
}
}
return null;
}