Java源码示例:com.github.javaparser.ast.expr.ObjectCreationExpr
示例1
private MethodDeclaration createInstanceMethod(String processInstanceFQCN) {
MethodDeclaration methodDeclaration = new MethodDeclaration();
ReturnStmt returnStmt = new ReturnStmt(
new ObjectCreationExpr()
.setType(processInstanceFQCN)
.setArguments(NodeList.nodeList(
new ThisExpr(),
new NameExpr("value"),
createProcessRuntime())));
methodDeclaration.setName("createInstance")
.addModifier(Modifier.Keyword.PUBLIC)
.addParameter(modelTypeName, "value")
.setType(processInstanceFQCN)
.setBody(new BlockStmt()
.addStatement(returnStmt));
return methodDeclaration;
}
示例2
private MethodDeclaration createInstanceWithBusinessKeyMethod(String processInstanceFQCN) {
MethodDeclaration methodDeclaration = new MethodDeclaration();
ReturnStmt returnStmt = new ReturnStmt(
new ObjectCreationExpr()
.setType(processInstanceFQCN)
.setArguments(NodeList.nodeList(
new ThisExpr(),
new NameExpr("value"),
new NameExpr(BUSINESS_KEY),
createProcessRuntime())));
methodDeclaration.setName("createInstance")
.addModifier(Modifier.Keyword.PUBLIC)
.addParameter(String.class.getCanonicalName(), BUSINESS_KEY)
.addParameter(modelTypeName, "value")
.setType(processInstanceFQCN)
.setBody(new BlockStmt()
.addStatement(returnStmt));
return methodDeclaration;
}
示例3
public ObjectCreationExpr newInstance() {
if (annotator != null) {
return new ObjectCreationExpr()
.setType(StaticProcessConfig.class.getCanonicalName())
.addArgument(new MethodCallExpr(METHOD_EXTRACT_WORK_ITEM_HANDLER_CONFIG))
.addArgument(new MethodCallExpr(METHOD_EXTRACT_PROCESS_EVENT_LISTENER_CONFIG))
.addArgument(new MethodCallExpr(METHOD_EXTRACT_UNIT_OF_WORK_MANAGER))
.addArgument(new MethodCallExpr(METHOD_EXTRACT_JOBS_SERVICE));
} else {
return new ObjectCreationExpr()
.setType(StaticProcessConfig.class.getCanonicalName())
.addArgument(new NameExpr(VAR_DEFAULT_WORK_ITEM_HANDLER_CONFIG))
.addArgument(new NameExpr(VAR_DEFAULT_PROCESS_EVENT_LISTENER_CONFIG))
.addArgument(new NameExpr(VAR_DEFAULT_UNIT_OF_WORK_MANAGER))
.addArgument(new NameExpr(VAR_DEFAULT_JOBS_SEVICE));
}
}
示例4
@Override
public void visitNode(String factoryField, ForEachNode node, BlockStmt body, VariableScope variableScope, ProcessMetaData metadata) {
body.addStatement(getAssignedFactoryMethod(factoryField, ForEachNodeFactory.class, getNodeId(node), getNodeKey(), new LongLiteralExpr(node.getId())))
.addStatement(getNameMethod(node, "ForEach"));
visitMetaData(node.getMetaData(), body, getNodeId(node));
body.addStatement(getFactoryMethod(getNodeId(node), METHOD_COLLECTION_EXPRESSION, new StringLiteralExpr(stripExpression(node.getCollectionExpression()))))
.addStatement(getFactoryMethod(getNodeId(node), METHOD_VARIABLE, new StringLiteralExpr(node.getVariableName()),
new ObjectCreationExpr(null, new ClassOrInterfaceType(null, ObjectDataType.class.getSimpleName()), NodeList.nodeList(
new StringLiteralExpr(node.getVariableType().getStringType())
))));
if (node.getOutputCollectionExpression() != null) {
body.addStatement(getFactoryMethod(getNodeId(node), METHOD_OUTPUT_COLLECTION_EXPRESSION, new StringLiteralExpr(stripExpression(node.getOutputCollectionExpression()))))
.addStatement(getFactoryMethod(getNodeId(node), METHOD_OUTPUT_VARIABLE, new StringLiteralExpr(node.getOutputVariableName()),
new ObjectCreationExpr(null, new ClassOrInterfaceType(null, ObjectDataType.class.getSimpleName()), NodeList.nodeList(
new StringLiteralExpr(node.getOutputVariableType().getStringType())
))));
}
// visit nodes
visitNodes(getNodeId(node), node.getNodes(), body, ((VariableScope) node.getCompositeNode().getDefaultContext(VariableScope.VARIABLE_SCOPE)), metadata);
body.addStatement(getFactoryMethod(getNodeId(node), METHOD_LINK_INCOMING_CONNECTIONS, new LongLiteralExpr(node.getLinkedIncomingNode(org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE).getNodeId())))
.addStatement(getFactoryMethod(getNodeId(node), METHOD_LINK_OUTGOING_CONNECTIONS, new LongLiteralExpr(node.getLinkedOutgoingNode(org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE).getNodeId())))
.addStatement(getDoneMethod(getNodeId(node)));
}
示例5
public void addProcessToApplication(ProcessGenerator r) {
ObjectCreationExpr newProcess = new ObjectCreationExpr()
.setType(r.targetCanonicalName())
.addArgument("application");
IfStmt byProcessId = new IfStmt(new MethodCallExpr(new StringLiteralExpr(r.processId()), "equals", NodeList.nodeList(new NameExpr("processId"))),
new ReturnStmt(new MethodCallExpr(
newProcess,
"configure")),
null);
byProcessIdMethodDeclaration
.getBody()
.orElseThrow(() -> new NoSuchElementException("A method declaration doesn't contain a body!"))
.addStatement(byProcessId);
}
示例6
private void generateResultClass(ClassOrInterfaceDeclaration clazz, MethodDeclaration toResultMethod) {
ClassOrInterfaceDeclaration resultClass = new ClassOrInterfaceDeclaration(new NodeList<Modifier>(Modifier.publicModifier(), Modifier.staticModifier()), false, "Result");
clazz.addMember(resultClass);
ConstructorDeclaration constructor = resultClass.addConstructor(Modifier.Keyword.PUBLIC);
BlockStmt constructorBody = constructor.createBody();
ObjectCreationExpr resultCreation = new ObjectCreationExpr();
resultCreation.setType("Result");
BlockStmt resultMethodBody = toResultMethod.createBody();
resultMethodBody.addStatement(new ReturnStmt(resultCreation));
query.getBindings().forEach((name, type) -> {
resultClass.addField(type, name, Modifier.Keyword.PRIVATE, Modifier.Keyword.FINAL);
MethodDeclaration getterMethod = resultClass.addMethod("get" + ucFirst(name), Modifier.Keyword.PUBLIC);
getterMethod.setType(type);
BlockStmt body = getterMethod.createBody();
body.addStatement(new ReturnStmt(new NameExpr(name)));
constructor.addAndGetParameter(type, name);
constructorBody.addStatement(new AssignExpr(new NameExpr("this." + name), new NameExpr(name), AssignExpr.Operator.ASSIGN));
MethodCallExpr callExpr = new MethodCallExpr(new NameExpr("tuple"), "get");
callExpr.addArgument(new StringLiteralExpr(name));
resultCreation.addArgument(new CastExpr(classToReferenceType(type), callExpr));
});
}
示例7
private MethodDeclaration genericFactoryById() {
ClassOrInterfaceType returnType = new ClassOrInterfaceType(null, RuleUnit.class.getCanonicalName())
.setTypeArguments(new WildcardType());
SwitchStmt switchStmt = new SwitchStmt();
switchStmt.setSelector(new NameExpr("fqcn"));
for (RuleUnitGenerator ruleUnit : ruleUnits) {
SwitchEntry switchEntry = new SwitchEntry();
switchEntry.getLabels().add(new StringLiteralExpr(ruleUnit.getRuleUnitDescription().getCanonicalName()));
ObjectCreationExpr ruleUnitConstructor = new ObjectCreationExpr()
.setType(ruleUnit.targetCanonicalName())
.addArgument("application");
switchEntry.getStatements().add(new ReturnStmt(ruleUnitConstructor));
switchStmt.getEntries().add(switchEntry);
}
SwitchEntry defaultEntry = new SwitchEntry();
defaultEntry.getStatements().add(new ThrowStmt(new ObjectCreationExpr().setType(UnsupportedOperationException.class.getCanonicalName())));
switchStmt.getEntries().add(defaultEntry);
return new MethodDeclaration()
.addModifier(Modifier.Keyword.PROTECTED)
.setType(returnType)
.setName("create")
.addParameter(String.class, "fqcn")
.setBody(new BlockStmt().addStatement(switchStmt));
}
示例8
public void classDeclaration(ClassOrInterfaceDeclaration cls) {
cls.setName(targetTypeName)
.setModifiers(Modifier.Keyword.PUBLIC)
.getExtendedTypes().get(0).setTypeArguments(nodeList(new ClassOrInterfaceType(null, typeName)));
if (annotator != null) {
annotator.withSingletonComponent(cls);
cls.findFirst(ConstructorDeclaration.class, c -> !c.getParameters().isEmpty()) // non-empty constructor
.ifPresent(annotator::withInjection);
}
String ruleUnitInstanceFQCN = RuleUnitInstanceGenerator.qualifiedName(packageName, typeName);
cls.findAll(ConstructorDeclaration.class).forEach(this::setClassName);
cls.findAll(ObjectCreationExpr.class, o -> o.getType().getNameAsString().equals("$InstanceName$"))
.forEach(o -> o.setType(ruleUnitInstanceFQCN));
cls.findAll(ObjectCreationExpr.class, o -> o.getType().getNameAsString().equals("$Application$"))
.forEach(o -> o.setType(applicationPackageName + ".Application"));
cls.findAll(ObjectCreationExpr.class, o -> o.getType().getNameAsString().equals("$RuleModelName$"))
.forEach(o -> o.setType(packageName + "." + generatedSourceFile + "_" + typeName));
cls.findAll(MethodDeclaration.class, m -> m.getType().asString().equals("$InstanceName$"))
.stream()
.map(m -> m.setType(ruleUnitInstanceFQCN))
.flatMap(m -> m.getParameters().stream())
.filter(p -> p.getType().asString().equals("$ModelName$"))
.forEach(o -> o.setType(typeName));
cls.findAll( MethodCallExpr.class).stream()
.flatMap( mCall -> mCall.getArguments().stream() )
.filter( e -> e.isNameExpr() && e.toNameExpr().get().getNameAsString().equals( "$ModelClass$" ) )
.forEach( e -> e.toNameExpr().get().setName( typeName + ".class" ) );
cls.findAll(TypeParameter.class)
.forEach(tp -> tp.setName(typeName));
}
示例9
public ObjectCreationExpr newInstance() {
if (annotator != null) {
return new ObjectCreationExpr()
.setType(StaticRuleConfig.class.getCanonicalName())
.addArgument(new MethodCallExpr(METHOD_EXTRACT_RULE_EVENT_LISTENER_CONFIG));
} else {
return new ObjectCreationExpr()
.setType(StaticRuleConfig.class.getCanonicalName())
.addArgument(new NameExpr(VAR_DEFAULT_RULE_EVENT_LISTENER_CONFIG));
}
}
示例10
@Override
public ClassOrInterfaceDeclaration classDeclaration() {
// FieldDeclaration dmnRuntimeField = new FieldDeclaration().addModifier(Modifier.Keyword.STATIC)
// .addVariable(new VariableDeclarator().setType(DMNRuntime.class.getCanonicalName())
// .setName("dmnRuntime")
// .setInitializer(new MethodCallExpr("org.kie.dmn.kogito.rest.quarkus.DMNKogitoQuarkus.createGenericDMNRuntime")));
// ClassOrInterfaceDeclaration cls = super.classDeclaration();
// cls.addModifier(Modifier.Keyword.STATIC);
// cls.addMember(dmnRuntimeField);
//
// MethodDeclaration getDecisionMethod = new MethodDeclaration().setName("getDecision")
// .setType(Decision.class.getCanonicalName())
// .addParameter(new Parameter(StaticJavaParser.parseType(String.class.getCanonicalName()), "namespace"))
// .addParameter(new Parameter(StaticJavaParser.parseType(String.class.getCanonicalName()), "name"))
// ;
// cls.addMember(getDecisionMethod);
CompilationUnit clazz = StaticJavaParser.parse(this.getClass().getResourceAsStream(TEMPLATE_JAVA));
ClassOrInterfaceDeclaration typeDeclaration = (ClassOrInterfaceDeclaration) clazz.getTypes().get(0);
ClassOrInterfaceType applicationClass = StaticJavaParser.parseClassOrInterfaceType(applicationCanonicalName);
ClassOrInterfaceType inputStreamReaderClass = StaticJavaParser.parseClassOrInterfaceType(java.io.InputStreamReader.class.getCanonicalName());
for (DMNResource resource : resources) {
MethodCallExpr getResAsStream = getReadResourceMethod( applicationClass, resource );
ObjectCreationExpr isr = new ObjectCreationExpr().setType(inputStreamReaderClass).addArgument(getResAsStream);
Optional<FieldDeclaration> dmnRuntimeField = typeDeclaration.getFieldByName("dmnRuntime");
Optional<Expression> initalizer = dmnRuntimeField.flatMap(x -> x.getVariable(0).getInitializer());
if (initalizer.isPresent()) {
initalizer.get().asMethodCallExpr().addArgument(isr);
} else {
throw new RuntimeException("The template " + TEMPLATE_JAVA + " has been modified.");
}
}
if (useTracing) {
VariableDeclarator execIdSupplierVariable = typeDeclaration.getFieldByName("execIdSupplier")
.map(x -> x.getVariable(0))
.orElseThrow(() -> new RuntimeException("Can't find \"execIdSupplier\" field in " + TEMPLATE_JAVA));
execIdSupplierVariable.setInitializer(newObject(DmnExecutionIdSupplier.class));
}
return typeDeclaration;
}
示例11
public ObjectCreationExpr newInstance() {
if (annotator != null) {
return new ObjectCreationExpr()
.setType(StaticDecisionConfig.class.getCanonicalName())
.addArgument(new MethodCallExpr(METHOD_EXTRACT_DECISION_EVENT_LISTENER_CONFIG));
} else {
return new ObjectCreationExpr()
.setType(StaticDecisionConfig.class.getCanonicalName())
.addArgument(new NameExpr(VAR_DEFAULT_DECISION_EVENT_LISTENER_CONFIG));
}
}
示例12
@Override
public FieldDeclaration fieldDeclaration() {
ObjectCreationExpr objectCreationExpr = new ObjectCreationExpr().setType( sectionClassName );
if (useApplication()) {
objectCreationExpr.addArgument( "this" );
}
return new FieldDeclaration()
.addVariable(
new VariableDeclarator()
.setType( sectionClassName )
.setName(methodName)
.setInitializer(objectCreationExpr) );
}
示例13
private void newInstanceTest(final ProcessConfigGenerator processConfigGenerator, final Class<?> expectedArgumentType) {
ObjectCreationExpr expression = new ConfigGenerator("org.kie.kogito.test").withProcessConfig(processConfigGenerator).newInstance();
assertThat(expression).isNotNull();
assertThat(expression.getType()).isNotNull();
assertThat(expression.getType().asString()).isEqualTo("org.kie.kogito.test.ApplicationConfig");
assertThat(expression.getArguments()).isNotNull();
assertThat(expression.getArguments()).hasSize(0);
}
示例14
protected void visitVariableScope(String contextNode, VariableScope variableScope, BlockStmt body, Set<String> visitedVariables) {
if (variableScope != null && !variableScope.getVariables().isEmpty()) {
for (Variable variable : variableScope.getVariables()) {
if (!visitedVariables.add(variable.getName())) {
continue;
}
String tags = (String) variable.getMetaData(Variable.VARIABLE_TAGS);
ClassOrInterfaceType variableType = new ClassOrInterfaceType(null, ObjectDataType.class.getSimpleName());
ObjectCreationExpr variableValue = new ObjectCreationExpr(null, variableType, new NodeList<>(new StringLiteralExpr(variable.getType().getStringType())));
body.addStatement(getFactoryMethod(contextNode, METHOD_VARIABLE,
new StringLiteralExpr(variable.getName()), variableValue,
new StringLiteralExpr(Variable.VARIABLE_TAGS), (tags != null ? new StringLiteralExpr(tags) : new NullLiteralExpr())));
}
}
}
示例15
public AssignExpr newInstance(String assignVarName) {
ClassOrInterfaceType type = new ClassOrInterfaceType(null, modelClassName);
return new AssignExpr(
new VariableDeclarationExpr(type, assignVarName),
new ObjectCreationExpr().setType(type),
AssignExpr.Operator.ASSIGN);
}
示例16
private void visitVariableScope(VariableScope variableScope, BlockStmt body, Set<String> visitedVariables) {
if (variableScope != null && !variableScope.getVariables().isEmpty()) {
for (Variable variable : variableScope.getVariables()) {
if (!visitedVariables.add(variable.getName())) {
continue;
}
String tags = (String) variable.getMetaData(Variable.VARIABLE_TAGS);
ClassOrInterfaceType variableType = new ClassOrInterfaceType(null, ObjectDataType.class.getSimpleName());
ObjectCreationExpr variableValue = new ObjectCreationExpr(null, variableType, new NodeList<>(new StringLiteralExpr(variable.getType().getStringType())));
body.addStatement(getFactoryMethod(FACTORY_FIELD_NAME, METHOD_VARIABLE, new StringLiteralExpr(variable.getName()), variableValue, new StringLiteralExpr(Variable.VARIABLE_TAGS), tags != null ? new StringLiteralExpr(tags) : new NullLiteralExpr()));
}
}
}
示例17
public AssignExpr newInstance() {
ClassOrInterfaceType type = new ClassOrInterfaceType(null, modelClassName);
return new AssignExpr(
new VariableDeclarationExpr(type, instanceVarName),
new ObjectCreationExpr().setType(type),
AssignExpr.Operator.ASSIGN);
}
示例18
@Override
public void visit(final ObjectCreationExpr n, final Void arg) {
printJavaComment(n.getComment(), arg);
if (n.getScope().isPresent()) {
n.getScope().get().accept(this, arg);
printer.print(".");
}
printer.print("new ");
printTypeArgs(n, arg);
if (!isNullOrEmpty(n.getTypeArguments().orElse(null))) {
printer.print(" ");
}
n.getType().accept(this, arg);
printArguments(n.getArguments(), arg);
if (n.getAnonymousClassBody().isPresent()) {
printer.println(" {");
printer.indent();
printMembers(n.getAnonymousClassBody().get(), arg);
printer.unindent();
printer.print("}");
}
}
示例19
private void parse(MethodDeclaration mdConfigRoute, File inJavaFile){
mdConfigRoute.getBody()
.ifPresent(blockStmt -> blockStmt.getStatements()
.stream()
.filter(statement -> statement instanceof ExpressionStmt)
.forEach(statement -> {
Expression expression = ((ExpressionStmt)statement).getExpression();
if(expression instanceof MethodCallExpr && ((MethodCallExpr)expression).getNameAsString().equals("add")){
NodeList<Expression> arguments = ((MethodCallExpr)expression).getArguments();
if(arguments.size() == 1 && arguments.get(0) instanceof ObjectCreationExpr){
String routeClassName = ((ObjectCreationExpr)((MethodCallExpr) expression).getArguments().get(0)).getType().getNameAsString();
File childRouteFile = ParseUtils.searchJavaFile(inJavaFile, routeClassName);
LogUtils.info("found child routes in file : %s" , childRouteFile.getName());
ParseUtils.compilationUnit(childRouteFile)
.getChildNodesByType(ClassOrInterfaceDeclaration.class)
.stream()
.filter(cd -> routeClassName.endsWith(cd.getNameAsString()))
.findFirst()
.ifPresent(cd ->{
LogUtils.info("found config() method, start to parse child routes in file : %s" , childRouteFile.getName());
cd.getMethodsByName("config").stream().findFirst().ifPresent(m ->{
parse(m, childRouteFile);
});
});
}else{
String basicUrl = Utils.removeQuotations(arguments.get(0).toString());
String controllerClass = arguments.get(1).toString();
String controllerFilePath = getControllerFilePath(inJavaFile, controllerClass);
routeNodeList.add(new RouteNode(basicUrl, controllerFilePath));
}
}
}));
}
示例20
@Override public ObjectCreationExpr doMerge(ObjectCreationExpr first, ObjectCreationExpr second) {
ObjectCreationExpr oce = new ObjectCreationExpr();
oce.setScope(mergeSingle(first.getScope(),second.getScope()));
oce.setType(mergeSingle(first.getType(),second.getType()));
oce.setTypeArgs(mergeCollectionsInOrder(first.getTypeArgs(),second.getTypeArgs()));
oce.setArgs(mergeCollectionsInOrder(first.getArgs(),second.getArgs()));
oce.setAnonymousClassBody(mergeCollections(first.getAnonymousClassBody(),second.getAnonymousClassBody()));
return oce;
}
示例21
@Override public boolean doIsEquals(ObjectCreationExpr first, ObjectCreationExpr second) {
if(!isEqualsUseMerger(first.getScope(),second.getScope())) return false;
if(!isEqualsUseMerger(first.getType(),second.getType())) return false;
if(!isEqualsUseMerger(first.getTypeArgs(),second.getTypeArgs())) return false;
if(!isEqualsUseMerger(first.getArgs(),second.getArgs())) return false;
return true;
}
示例22
private void processSpecialNodeTypes(ObjectCreationExpr node) {
Type type = node.getType();
if (isRefType(type, "LinkedQueueNode")) {
node.setType(simpleParametricType("LinkedQueueAtomicNode", "E"));
} else if (isRefArray(type, "E")) {
node.setType(atomicRefArrayType((ArrayType) type));
}
}
示例23
@Nonnull
public static String getTypeName(@Nonnull Node node) {
List<Node> anonymousClasses = newArrayList();
StringBuilder buffy = new StringBuilder();
Node loopNode = node;
for (; ; ) {
if (ObjectCreationExpr.class.isInstance(loopNode)) {
if (!isEmpty(ObjectCreationExpr.class.cast(loopNode).getAnonymousClassBody())) {
anonymousClasses.add(loopNode);
}
} else if (TypeDeclarationStmt.class.isInstance(loopNode)) {
anonymousClasses.add(loopNode);
} else if (TypeDeclaration.class.isInstance(loopNode)
&& !TypeDeclarationStmt.class.isInstance(loopNode.getParentNode())) {
TypeDeclaration typeDeclaration = TypeDeclaration.class.cast(loopNode);
prependSeparatorIfNecessary('$', buffy).insert(0, typeDeclaration.getName());
appendAnonymousClasses(anonymousClasses, typeDeclaration, buffy);
} else if (CompilationUnit.class.isInstance(loopNode)) {
if (buffy.length() == 0) {
buffy.append("package-info");
}
final CompilationUnit compilationUnit = CompilationUnit.class.cast(loopNode);
if (compilationUnit.getPackage() != null) {
prepend(compilationUnit.getPackage().getName(), buffy);
}
}
loopNode = loopNode.getParentNode();
if (loopNode == null) {
return buffy.toString();
}
}
}
示例24
public ObjectCreationExpr newInstance() {
return new ObjectCreationExpr()
.setType(targetCanonicalName);
}
示例25
public static ObjectCreationExpr newObject(Class<?> type) {
return newObject(type.getCanonicalName());
}
示例26
public static ObjectCreationExpr newObject(Class<?> type, Expression... arguments) {
return newObject(type.getCanonicalName(), arguments);
}
示例27
public static ObjectCreationExpr newObject(String type) {
return new ObjectCreationExpr(null, new ClassOrInterfaceType(null, type), new NodeList<>());
}
示例28
public static ObjectCreationExpr newObject(String type, Expression... arguments) {
return new ObjectCreationExpr(null, new ClassOrInterfaceType(null, type), NodeList.nodeList(arguments));
}
示例29
private void initializeProcessField(FieldDeclaration fd, ClassOrInterfaceDeclaration template) {
fd.getVariable(0).setInitializer(new ObjectCreationExpr().setType(processClazzName));
}
示例30
private void initializeApplicationField(FieldDeclaration fd, ClassOrInterfaceDeclaration template) {
fd.getVariable(0).setInitializer(new ObjectCreationExpr().setType(appCanonicalName));
}