add pool field to static new class

This commit is contained in:
金戟 2020-05-16 12:03:29 +08:00
parent f76da5d9b0
commit 44eda2be06

View File

@ -5,7 +5,9 @@ import com.squareup.javapoet.*;
import javax.lang.model.element.Modifier; import javax.lang.model.element.Modifier;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* Generate global n.e class code * Generate global n.e class code
@ -18,11 +20,19 @@ public class StaticNewClassGenerator {
return JavaFile.builder(ConstPool.SN_PKG, return JavaFile.builder(ConstPool.SN_PKG,
TypeSpec.classBuilder(ConstPool.SN_CLS) TypeSpec.classBuilder(ConstPool.SN_CLS)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addField(buildStaticPoolField())
.addMethod(buildStaticNewMethod()) .addMethod(buildStaticNewMethod())
.build()) .build())
.build().toString(); .build().toString();
} }
private FieldSpec buildStaticPoolField() {
return FieldSpec.builder(ParameterizedTypeName.get(Map.class, Class.class, Object.class), "pool", Modifier.PUBLIC)
.addModifiers(Modifier.STATIC)
.initializer("new $T<>()", HashMap.class)
.build();
}
private MethodSpec buildStaticNewMethod() { private MethodSpec buildStaticNewMethod() {
TypeVariableName typeVariable = TypeVariableName.get("T"); TypeVariableName typeVariable = TypeVariableName.get("T");
MethodSpec.Builder builder = MethodSpec.methodBuilder(ConstPool.SN_METHOD) MethodSpec.Builder builder = MethodSpec.methodBuilder(ConstPool.SN_METHOD)
@ -41,6 +51,15 @@ public class StaticNewClassGenerator {
.beginControlFlow("for (Object o : args)") .beginControlFlow("for (Object o : args)")
.addStatement("pts.add(o.getClass())") .addStatement("pts.add(o.getClass())")
.endControlFlow() .endControlFlow()
.beginControlFlow("if (!pool.isEmpty())")
.beginControlFlow("try")
.addStatement("T obj = (T)pool.get(type)")
.beginControlFlow("if (obj != null)")
.addStatement("return obj")
.endControlFlow()
.nextControlFlow("catch (Exception e)")
.endControlFlow()
.endControlFlow()
.beginControlFlow("try") .beginControlFlow("try")
.addStatement("return type.getConstructor(pts.toArray(new Class[0])).newInstance(args)") .addStatement("return type.getConstructor(pts.toArray(new Class[0])).newInstance(args)")
.nextControlFlow("catch (Exception e)") .nextControlFlow("catch (Exception e)")