com.github.javaparser.ast.body.VariableDeclarator Java Examples
The following examples show how to use
com.github.javaparser.ast.body.VariableDeclarator.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Reverser.java From android-reverse-r with Apache License 2.0 | 6 votes |
@Override public void visit(ClassOrInterfaceDeclaration clazz, Object arg) { for (BodyDeclaration member : clazz.getMembers()) { if (member instanceof ClassOrInterfaceDeclaration) visit((ClassOrInterfaceDeclaration)member, arg); else if (member instanceof FieldDeclaration) { FieldDeclaration field = (FieldDeclaration)member; String type = null != field.getType() ? field.getType().toString() : ""; if (type.equals("int")) { VariableDeclarator variable = field.getVariables().stream().findFirst().get(); String name = variable.getId().toString(); Integer value = null != variable.getInit() ? Integer.parseInt(variable.getInit().toString()) : 0; // decimal value of 0x7f000000, which is what AAPT starts numbering at - https://stackoverflow.com/questions/6517151/how-does-the-mapping-between-android-resources-and-resources-id-work/6646113#6646113 if (value >= 2130706432) { name = "R." + ((ClassOrInterfaceDeclaration)field.getParentNode()).getName() + "." + name; transform.put(value, name); } } } } }
Example #2
Source File: RuleUnitMetaModel.java From kogito-runtimes with Apache License 2.0 | 6 votes |
public Statement injectCollection( String targetUnitVar, String sourceProcVar) { BlockStmt blockStmt = new BlockStmt(); RuleUnitVariable v = ruleUnitDescription.getVar(targetUnitVar); String appendMethod = appendMethodOf(v.getType()); blockStmt.addStatement(assignVar(v)); blockStmt.addStatement( iterate(new VariableDeclarator() .setType("Object").setName("it"), new NameExpr(sourceProcVar)) .setBody(new ExpressionStmt( new MethodCallExpr() .setScope(new NameExpr(localVarName(v))) .setName(appendMethod) .addArgument(new NameExpr("it"))))); return blockStmt; }
Example #3
Source File: ImmutableBeanGenerator.java From state-machine with Apache License 2.0 | 6 votes |
private static void writeEquals(PrintStream s, Map<String, String> imports, String indent, ClassOrInterfaceDeclaration c, List<VariableDeclarator> vars) { s.format("\n\n%s@%s", indent, resolve(imports, Override.class)); s.format("\n%spublic boolean equals(Object o) {", indent); s.format("\n%s%sif (o == null) {", indent, indent); s.format("\n%s%s%sreturn false;", indent, indent, indent); s.format("\n%s%s} else if (!(o instanceof %s)) {", indent, indent, c.getName()); s.format("\n%s%s%sreturn false;", indent, indent, indent); s.format("\n%s%s} else {", indent, indent); if (vars.isEmpty()) { s.format("\n%s%s%sreturn true;", indent, indent, indent); } else { s.format("\n%s%s%s%s other = (%s) o;", indent, indent, indent, c.getName(), c.getName()); s.format("\n%s%s%sreturn", indent, indent, indent); String expression = vars.stream() /// .map(x -> String.format("%s.deepEquals(this.%s, other.%s)", // resolve(imports, Objects.class), x.getName(), x.getName())) // .collect(Collectors.joining(String.format("\n%s%s%s%s&& ", indent, indent, indent, indent))); s.format("\n%s%s%s%s%s;", indent, indent, indent, indent, expression); } s.format("\n%s%s}", indent, indent); s.format("\n%s}", indent); }
Example #4
Source File: ASTHelper.java From stategen with GNU Affero General Public License v3.0 | 6 votes |
/** * Gets the field declaration map. * * @param <T> the generic type * @param node the class declaration * @param type the type * @return the field declaration map */ static <T extends BodyDeclaration> Map<String, T> getBodyDeclarationMap(Node node, Class<T> type) { List<Node> children = node.getChildNodes(); if (CollectionUtil.isEmpty(children)) { return new HashMap<String, T>(0); } Map<String, T> bodyMap = new CaseInsensitiveHashMap<T>(children.size()); List<T> bodyDeclarations = getNodesByType(node, type); for (T bodyDeclaration : bodyDeclarations) { if (bodyDeclaration instanceof FieldDeclaration) { FieldDeclaration fieldDeclaration = (FieldDeclaration) bodyDeclaration; VariableDeclarator variableDeclaratorId = getOneNodesByType(fieldDeclaration, VariableDeclarator.class); bodyMap.put(variableDeclaratorId.getName().toString(), bodyDeclaration); } else if (bodyDeclaration instanceof MethodDeclaration) { MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration; bodyMap.put(methodDeclaration.getNameAsString(), bodyDeclaration); } } return bodyMap; }
Example #5
Source File: PrettyPrintVisitor.java From stategen with GNU Affero General Public License v3.0 | 6 votes |
@Override public void visit(final FieldDeclaration n, final Void arg) { printOrphanCommentsBeforeThisChildNode(n); printJavaComment(n.getComment(), arg); printMemberAnnotations(n.getAnnotations(), arg); printModifiers(n.getModifiers()); if (!n.getVariables().isEmpty()) { n.getMaximumCommonType().accept(this, arg); } printer.print(" "); for (final Iterator<VariableDeclarator> i = n.getVariables().iterator(); i.hasNext(); ) { final VariableDeclarator var = i.next(); var.accept(this, arg); if (i.hasNext()) { printer.print(", "); } } printer.print(";"); }
Example #6
Source File: PrettyPrintVisitor.java From stategen with GNU Affero General Public License v3.0 | 6 votes |
@Override public void visit(final VariableDeclarator n, final Void arg) { printJavaComment(n.getComment(), arg); n.getName().accept(this, arg); Type commonType = n.getAncestorOfType(NodeWithVariables.class).get().getMaximumCommonType(); Type type = n.getType(); ArrayType arrayType = null; for (int i = commonType.getArrayLevel(); i < type.getArrayLevel(); i++) { if (arrayType == null) { arrayType = (ArrayType) type; } else { arrayType = (ArrayType) arrayType.getComponentType(); } printAnnotations(arrayType.getAnnotations(), true, arg); printer.print("[]"); } if (n.getInitializer().isPresent()) { printer.print(" = "); n.getInitializer().get().accept(this, arg); } }
Example #7
Source File: PrettyPrintVisitor.java From stategen with GNU Affero General Public License v3.0 | 6 votes |
@Override public void visit(final VariableDeclarationExpr n, final Void arg) { printJavaComment(n.getComment(), arg); printAnnotations(n.getAnnotations(), false, arg); printModifiers(n.getModifiers()); if (!n.getVariables().isEmpty()) { n.getMaximumCommonType().accept(this, arg); } printer.print(" "); for (final Iterator<VariableDeclarator> i = n.getVariables().iterator(); i.hasNext(); ) { final VariableDeclarator v = i.next(); v.accept(this, arg); if (i.hasNext()) { printer.print(", "); } } }
Example #8
Source File: DecisionConfigGenerator.java From kogito-runtimes with Apache License 2.0 | 6 votes |
public List<BodyDeclaration<?>> members() { if (annotator != null) { FieldDeclaration delcFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration() .addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), DecisionEventListenerConfig.class), VAR_DECISION_EVENT_LISTENER_CONFIG))); members.add(delcFieldDeclaration); FieldDeclaration drelFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration() .addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), DMNRuntimeEventListener.class), VAR_DMN_RUNTIME_EVENT_LISTENERS))); members.add(drelFieldDeclaration); members.add(generateExtractEventListenerConfigMethod()); members.add(generateMergeEventListenerConfigMethod()); } else { FieldDeclaration defaultDelcFieldDeclaration = new FieldDeclaration() .setModifiers(Modifier.Keyword.PRIVATE) .addVariable(new VariableDeclarator(new ClassOrInterfaceType(null, DecisionEventListenerConfig.class.getCanonicalName()), VAR_DEFAULT_DECISION_EVENT_LISTENER_CONFIG, newObject(DefaultDecisionEventListenerConfig.class))); members.add(defaultDelcFieldDeclaration); } return members; }
Example #9
Source File: RuleConfigGenerator.java From kogito-runtimes with Apache License 2.0 | 6 votes |
public List<BodyDeclaration<?>> members() { if (annotator != null) { FieldDeclaration relcFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration().addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), RuleEventListenerConfig.class), VAR_RULE_EVENT_LISTENER_CONFIGS))); members.add(relcFieldDeclaration); FieldDeclaration aelFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration().addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), AgendaEventListener.class), VAR_AGENDA_EVENT_LISTENERS))); members.add(aelFieldDeclaration); FieldDeclaration rrelFieldDeclaration = annotator.withOptionalInjection(new FieldDeclaration().addVariable(new VariableDeclarator(genericType(annotator.multiInstanceInjectionType(), RuleRuntimeEventListener.class), VAR_RULE_RUNTIME_EVENT_LISTENERS))); members.add(rrelFieldDeclaration); members.add(generateExtractEventListenerConfigMethod()); members.add(generateMergeEventListenerConfigMethod()); } else { FieldDeclaration defaultRelcFieldDeclaration = new FieldDeclaration() .setModifiers(Modifier.Keyword.PRIVATE) .addVariable(new VariableDeclarator(new ClassOrInterfaceType(null, RuleEventListenerConfig.class.getCanonicalName()), VAR_DEFAULT_RULE_EVENT_LISTENER_CONFIG, newObject(DefaultRuleEventListenerConfig.class))); members.add(defaultRelcFieldDeclaration); } return members; }
Example #10
Source File: FinalRClassBuilder.java From Briefness with Apache License 2.0 | 6 votes |
private static void addResourceField(TypeSpec.Builder resourceType, VariableDeclarator variable, ClassName annotation) { String fieldName = variable.getNameAsString(); String fieldValue = variable.getInitializer() .map(Node::toString) .orElseThrow( () -> new IllegalStateException("Field " + fieldName + " missing initializer")); FieldSpec.Builder fieldSpecBuilder = FieldSpec.builder(int.class, fieldName) .addModifiers(PUBLIC, STATIC, FINAL) .initializer(fieldValue); if (annotation != null) { fieldSpecBuilder.addAnnotation(annotation); } resourceType.addField(fieldSpecBuilder.build()); }
Example #11
Source File: TestCodeVisitor.java From CodeDefenders with GNU Lesser General Public License v3.0 | 6 votes |
@Override public void visit(VariableDeclarator stmt, Void args) { if (!isValid) { return; } Optional<Expression> initializer = stmt.getInitializer(); if (initializer.isPresent()) { String initString = initializer.get().toString(); if (initString.startsWith("System.*") || initString.startsWith("Random.*") || initString.contains("Thread")) { messages.add("Test contains an invalid variable declaration: " + initString); isValid = false; } } super.visit(stmt, args); }
Example #12
Source File: ClassCodeAnalyser.java From CodeDefenders with GNU Lesser General Public License v3.0 | 6 votes |
private static void extractResultsFromFieldDeclaration(FieldDeclaration f, CodeAnalysisResult result) { final boolean compileTimeConstant = f.isFinal() && ((f.getCommonType() instanceof PrimitiveType) || (String.class.getSimpleName().equals(f.getElementType().asString()))); for (VariableDeclarator v : f.getVariables()) { for (int line = v.getBegin().get().line; line <= v.getEnd().get().line; line++) { if (compileTimeConstant) { logger.debug("Found compile-time constant " + v); // compile time targets are non coverable, too result.compileTimeConstant(line); result.nonCoverableCode(line); } if (!v.getInitializer().isPresent()) { // non initialized fields are non coverable result.nonInitializedField(line); result.nonCoverableCode(line); } } } }
Example #13
Source File: LocationSearcher.java From meghanada-server with GNU General Public License v3.0 | 6 votes |
@SuppressWarnings("try") private static Location getFieldLocation( SearchContext context, File targetFile, FieldDeclaration declaration) throws IOException { try (TelemetryUtils.ScopedSpan scope = TelemetryUtils.startScopedSpan("LocationSearcher.getFieldLocation")) { TelemetryUtils.ScopedSpan.addAnnotation( TelemetryUtils.annotationBuilder().put("targetFile", targetFile.getPath()).build("args")); final List<VariableDeclarator> variables = declaration.getVariables(); for (final VariableDeclarator variable : variables) { final SimpleName simpleName = variable.getName(); final String name = simpleName.getIdentifier(); final Optional<Position> begin = simpleName.getBegin(); if (name.equals(context.name) && begin.isPresent()) { final Position position = begin.get(); return new Location(targetFile.getCanonicalPath(), position.line, position.column); } } return null; } }
Example #14
Source File: ImmutableBeanGenerator.java From state-machine with Apache License 2.0 | 5 votes |
private static void writeWiths(PrintStream s, String indent, ClassOrInterfaceDeclaration c, List<VariableDeclarator> vars) { vars.stream() // .forEach(x -> { s.format("\n\n%spublic %s with%s(%s %s) {", indent, c.getName(), capFirst(x.getName().toString()), x.getType(), x.getName()); s.format("\n%s%sreturn new %s(%s);", indent, indent, c.getName(), // vars.stream() // .map(y -> y.getName().toString()) // .collect(Collectors.joining(", "))); s.format("\n%s}", indent); }); }
Example #15
Source File: ImmutableBeanGenerator.java From state-machine with Apache License 2.0 | 5 votes |
private static void writeGetters(PrintStream s, String indent, List<VariableDeclarator> vars) { // getters vars.stream() // .forEach(x -> { s.format("\n\n%spublic %s %s() {", indent, x.getType(), x.getName()); s.format("\n%s%sreturn %s;", indent, indent, x.getName()); s.format("\n%s}", indent); }); }
Example #16
Source File: ImmutableBeanGenerator.java From state-machine with Apache License 2.0 | 5 votes |
private static void writeCreateMethod(PrintStream s, String indent, ClassOrInterfaceDeclaration c, List<VariableDeclarator> vars) { if (!GENERATE_CREATE_METHOD) return; s.format("\n\n%spublic static %s create(%s) {", indent, c.getName(), // vars.stream() // .map(x -> x.getType() + " " + x.getName()) // .collect(Collectors.joining(", "))); s.format("\n%s%sreturn new %s(%s);", indent, indent, c.getName(), // vars.stream() // .map(x -> x.getName().toString()) // .collect(Collectors.joining(", "))); s.format("\n%s}", indent); }
Example #17
Source File: FieldIndexer.java From jql with MIT License | 5 votes |
public void index(FieldDeclaration fieldDeclaration, int typeId) { List<VariableDeclarator> variables = fieldDeclaration.getVariables(); for (VariableDeclarator variable : variables) { String name = variable.getNameAsString(); fieldDao.save(new Field(name, fieldDeclaration.getElementType().asString(), fieldDeclaration.isPublic(), fieldDeclaration.isStatic(), fieldDeclaration.isFinal(), fieldDeclaration.isTransient(), typeId)); } }
Example #18
Source File: ResourceOptimism.java From TestSmellDetector with GNU General Public License v3.0 | 5 votes |
@Override public void visit(VariableDeclarator n, Void arg) { if (currentMethod != null) { if (n.getType().asString().equals("File")) { methodVariables.add(n.getNameAsString()); } } else { if (n.getType().asString().equals("File")) { classVariables.add(n.getNameAsString()); } } super.visit(n, arg); }
Example #19
Source File: ImmutableBeanGenerator.java From state-machine with Apache License 2.0 | 5 votes |
private static void writeToString(PrintStream s, Map<String, String> imports, String indent, ClassOrInterfaceDeclaration c, List<VariableDeclarator> vars) { s.format("\n\n%s@%s", indent, resolve(imports, Override.class)); s.format("\n%spublic %s toString() {", indent, resolve(imports, String.class)); s.format("\n%s%s%s b = new %s();", indent, indent, resolve(imports, StringBuilder.class), resolve(imports, StringBuilder.class)); s.format("\n%s%sb.append(\"%s[\");", indent, indent, c.getName()); String ex = vars.stream() // .map(x -> String.format("\n%s%sb.append(\"%s=\" + this.%s);", indent, indent, x.getName(), x.getName())) // .collect(Collectors.joining(String.format("\n%s%sb.append(\",\");", indent, indent))); s.format("%s", ex); s.format("\n%s%sb.append(\"]\");", indent, indent); s.format("\n%s%sreturn b.toString();", indent, indent); s.format("\n%s}", indent); }
Example #20
Source File: ImmutableBeanGenerator.java From state-machine with Apache License 2.0 | 5 votes |
private static void writeHashCode(PrintStream s, Map<String, String> imports, String indent, List<VariableDeclarator> vars) { s.format("\n\n%s@%s", indent, resolve(imports, Override.class)); s.format("\n%spublic int hashCode() {", indent); s.format("\n%s%sreturn %s.hash(%s);", indent, indent, resolve(imports, Objects.class), // vars.stream() // .map(y -> y.getName().toString()) // .collect(Collectors.joining(", "))); s.format("\n%s}", indent); }
Example #21
Source File: ResourceOptimism.java From TestSmellDetector with GNU General Public License v3.0 | 5 votes |
@Override public void visit(FieldDeclaration n, Void arg) { for (VariableDeclarator variableDeclarator : n.getVariables()) { if (variableDeclarator.getType().equals("File")) { classVariables.add(variableDeclarator.getNameAsString()); } } super.visit(n, arg); }
Example #22
Source File: ImmutableBeanGenerator.java From state-machine with Apache License 2.0 | 5 votes |
private static void writeConstructor(PrintStream s, String indent, ClassOrInterfaceDeclaration c, List<FieldDeclaration> fields, List<VariableDeclarator> vars, Map<String, String> imports) { String typedParams = fields.stream() // .map(x -> declaration(x, imports)) // .collect(Collectors.joining(String.format(",\n%s ", indent))); s.format("\n\n%s@%s", indent, resolve(imports, JsonCreator.class)); s.format("\n%s%s(\n%s%s%s) {", indent, c.getName(), indent, " ", typedParams); vars.stream() // .forEach(x -> s.format("\n%s%sthis.%s = %s;", indent, indent, x.getName(), x.getName())); s.format("\n%s}", indent); }
Example #23
Source File: ImmutableBeanGenerator.java From state-machine with Apache License 2.0 | 5 votes |
private static String fieldDeclaration(String indent, FieldDeclaration x) { StringBuilder s = new StringBuilder(); for (Node n : x.getChildNodes()) { if (n instanceof VariableDeclarator) { VariableDeclarator v = (VariableDeclarator) n; s.append(NL + indent + "private final " + v.getType() + " " + v.getName() + ";"); } else if (n instanceof MarkerAnnotationExpr) { s.append(NL + indent + n); } } return s.toString(); }
Example #24
Source File: ImmutableBeanGenerator.java From state-machine with Apache License 2.0 | 5 votes |
private static VariableDeclarator variableDeclarator(FieldDeclaration f) { for (Node node : f.getChildNodes()) { if (node instanceof VariableDeclarator) { return (VariableDeclarator) node; } } throw new RuntimeException("declaration not found!"); }
Example #25
Source File: CodeValidator.java From CodeDefenders with GNU Lesser General Public License v3.0 | 5 votes |
private static Set<String> extractFieldNamesByType(TypeDeclaration td) { Set<String> fieldNames = new HashSet<>(); // Method signatures in the class including constructors for ( Object bd : td.getMembers()) { if (bd instanceof FieldDeclaration) { for (VariableDeclarator vd : ((FieldDeclaration) bd).getVariables()) { fieldNames.add(vd.getNameAsString()); } } else if (bd instanceof TypeDeclaration) { fieldNames.addAll(extractFieldNamesByType((TypeDeclaration) bd)); } } return fieldNames; }
Example #26
Source File: MutationVisitor.java From CodeDefenders with GNU Lesser General Public License v3.0 | 5 votes |
@Override public Node visit(VariableDeclarator stmt, Void args) { if (!isValid) { return stmt; } super.visit(stmt, args); if (stmt.getInitializer() != null && stmt.getInitializer().toString().startsWith("System.*")) { this.message = ValidationMessage.MUTATION_SYSTEM_DECLARATION; isValid = false; } return stmt; }
Example #27
Source File: ConfigurableEagerTest.java From CodeDefenders with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void visit(VariableDeclarator n, Void arg) { if (Objects.equals(fileType, TEST_FILE)) { if (productionClassName.equals(n.getType().asString())) { productionVariables.add(n.getNameAsString()); } } super.visit(n, arg); }
Example #28
Source File: TraceVisitor.java From JCTools with Apache License 2.0 | 5 votes |
@Override public void visit(VariableDeclarator n, Void arg) { out.println("VariableDeclarator: " + (extended ? n : n.getNameAsString() + " of type " + n.getType() + " init " + n.getInitializer().orElse(null))); super.visit(n, arg); }
Example #29
Source File: MigrateJCas.java From uima-uimaj with Apache License 2.0 | 5 votes |
private boolean hasTypeFields(NodeList<BodyDeclaration<?>> members) { boolean hasType = false; boolean hasTypeId = false; for (BodyDeclaration<?> bd : members) { if (bd instanceof FieldDeclaration) { FieldDeclaration f = (FieldDeclaration)bd; EnumSet<Modifier> m = f.getModifiers(); if (m.contains(Modifier.PUBLIC) && m.contains(Modifier.STATIC) && m.contains(Modifier.FINAL) // && // getTypeName(f.getType()).equals("int") ) { List<VariableDeclarator> vds = f.getVariables(); for (VariableDeclarator vd : vds) { if (vd.getType().equals(intType)) { String n = vd.getNameAsString(); if (n.equals("type")) hasType = true; if (n.equals("typeIndexID")) hasTypeId = true; if (hasTypeId && hasType) { return true; } } } } } } // end of for return false; }
Example #30
Source File: PersistenceGenerator.java From kogito-runtimes with Apache License 2.0 | 5 votes |
protected void fileSystemBasedPersistence(List<GeneratedFile> generatedFiles) { ClassOrInterfaceDeclaration persistenceProviderClazz = new ClassOrInterfaceDeclaration() .setName("KogitoProcessInstancesFactoryImpl") .setModifiers(Modifier.Keyword.PUBLIC) .addExtendedType("org.kie.kogito.persistence.KogitoProcessInstancesFactory"); CompilationUnit compilationUnit = new CompilationUnit("org.kie.kogito.persistence"); compilationUnit.getTypes().add(persistenceProviderClazz); if (useInjection()) { annotator.withApplicationComponent(persistenceProviderClazz); FieldDeclaration pathField = new FieldDeclaration().addVariable(new VariableDeclarator() .setType(new ClassOrInterfaceType(null, new SimpleName(Optional.class.getCanonicalName()), NodeList.nodeList(new ClassOrInterfaceType(null, String.class.getCanonicalName())))) .setName(PATH_NAME)); annotator.withConfigInjection(pathField, KOGITO_PERSISTENCE_FS_PATH_PROP); // allow to inject path for the file system storage BlockStmt pathMethodBody = new BlockStmt(); pathMethodBody.addStatement(new ReturnStmt(new MethodCallExpr(new NameExpr(PATH_NAME), "orElse").addArgument(new StringLiteralExpr("/tmp")))); MethodDeclaration pathMethod = new MethodDeclaration() .addModifier(Keyword.PUBLIC) .setName(PATH_NAME) .setType(String.class) .setBody(pathMethodBody); persistenceProviderClazz.addMember(pathField); persistenceProviderClazz.addMember(pathMethod); } String packageName = compilationUnit.getPackageDeclaration().map(pd -> pd.getName().toString()).orElse(""); String clazzName = packageName + "." + persistenceProviderClazz.findFirst(ClassOrInterfaceDeclaration.class).map(c -> c.getName().toString()).get(); generatedFiles.add(new GeneratedFile(GeneratedFile.Type.CLASS, clazzName.replace('.', '/') + ".java", compilationUnit.toString().getBytes(StandardCharsets.UTF_8))); persistenceProviderClazz.getMembers().sort(new BodyDeclarationComparator()); }