com.github.javaparser.ast.body.FieldDeclaration Java Examples
The following examples show how to use
com.github.javaparser.ast.body.FieldDeclaration.
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: BodyDeclarationComparator.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Override public int compare(BodyDeclaration<?> o1, BodyDeclaration<?> o2) { if (o1 instanceof FieldDeclaration && o2 instanceof FieldDeclaration) { return 0; } if (o1 instanceof FieldDeclaration && !(o2 instanceof FieldDeclaration)) { return -1; } if (o1 instanceof ConstructorDeclaration && o2 instanceof ConstructorDeclaration) { return 0; } if (o1 instanceof ConstructorDeclaration && o2 instanceof MethodDeclaration) { return -1; } if (o1 instanceof ConstructorDeclaration && o2 instanceof FieldDeclaration) { return 1; } return 1; }
Example #2
Source File: EntitySourceAnalyzer.java From enkan with Eclipse Public License 1.0 | 6 votes |
public List<EntityField> analyze(File source) throws IOException, ParseException { List<EntityField> entityFields = new ArrayList<>(); CompilationUnit cu = JavaParser.parse(source); cu.accept(new VoidVisitorAdapter<List<EntityField>>() { @Override public void visit(FieldDeclaration fd, List<EntityField> f) { if (fd.getAnnotations().stream().anyMatch(anno -> anno.getName().getName().equals("Column"))) { Class<?> type = null; switch (fd.getType().toString()) { case "String": type = String.class; break; case "Long": type = Long.class; break; case "Integer": type = Integer.class; break; case "boolean": type = boolean.class; break; } if (type == null) return; f.add(new EntityField( fd.getVariables().get(0).getId().getName(), type, fd.getAnnotations().stream().anyMatch(anno -> anno.getName().getName().equals("Id")))); } } }, entityFields); return entityFields; }
Example #3
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 #4
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 #5
Source File: FinalRClassBuilder.java From Briefness with Apache License 2.0 | 6 votes |
private static void addResourceType(List<String> supportedTypes, TypeSpec.Builder result, ClassOrInterfaceDeclaration node, boolean useLegacyTypes) { if (!supportedTypes.contains(node.getNameAsString())) { return; } String type = node.getNameAsString(); TypeSpec.Builder resourceType = TypeSpec.classBuilder(type) .addModifiers(PUBLIC, STATIC, FINAL); for (BodyDeclaration field : node.getMembers()) { if (field instanceof FieldDeclaration) { FieldDeclaration declaration = (FieldDeclaration) field; // Check that the field is an Int because styleable also contains Int arrays which can't be // used in annotations. if (isInt(declaration)) { addResourceField(resourceType, declaration.getVariables().get(0), getSupportAnnotationClass(type, useLegacyTypes)); } } } result.addType(resourceType.build()); }
Example #6
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 #7
Source File: IncrementalRuleCodegen.java From kogito-runtimes with Apache License 2.0 | 6 votes |
private void generateSessionUnits( List<org.kie.kogito.codegen.GeneratedFile> generatedFiles ) { for (KieBaseModel kBaseModel : kieModuleModel.getKieBaseModels().values()) { for (String sessionName : kBaseModel.getKieSessionModels().keySet()) { CompilationUnit cu = parse( getClass().getResourceAsStream( "/class-templates/SessionRuleUnitTemplate.java" ) ); ClassOrInterfaceDeclaration template = cu.findFirst( ClassOrInterfaceDeclaration.class ).get(); annotator.withNamedSingletonComponent(template, "$SessionName$"); template.setName( "SessionRuleUnit_" + sessionName ); template.findAll( FieldDeclaration.class).stream().filter( fd -> fd.getVariable(0).getNameAsString().equals("runtimeBuilder")).forEach( fd -> annotator.withInjection(fd)); template.findAll( StringLiteralExpr.class ).forEach( s -> s.setString( s.getValue().replace( "$SessionName$", sessionName ) ) ); generatedFiles.add(new org.kie.kogito.codegen.GeneratedFile( org.kie.kogito.codegen.GeneratedFile.Type.RULE, "org/drools/project/model/SessionRuleUnit_" + sessionName + ".java", log( cu.toString() ) )); } } }
Example #8
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 #9
Source File: ProcessesContainerGenerator.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@Override public CompilationUnit injectableClass() { CompilationUnit compilationUnit = parse(this.getClass().getResourceAsStream(RESOURCE)).setPackageDeclaration(packageName); ClassOrInterfaceDeclaration cls = compilationUnit .findFirst(ClassOrInterfaceDeclaration.class) .orElseThrow(() -> new NoSuchElementException("Compilation unit doesn't contain a class or interface declaration!")); cls.findAll(FieldDeclaration.class, fd -> fd.getVariable(0).getNameAsString().equals("processes")).forEach(fd -> { annotator.withInjection(fd); fd.getVariable(0).setType(new ClassOrInterfaceType(null, new SimpleName(annotator.multiInstanceInjectionType()), NodeList.nodeList(new ClassOrInterfaceType(null, new SimpleName(org.kie.kogito.process.Process.class.getCanonicalName()), NodeList.nodeList(new WildcardType(new ClassOrInterfaceType(null, Model.class.getCanonicalName()))))))); }); annotator.withApplicationComponent(cls); return compilationUnit; }
Example #10
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 #11
Source File: ReorderModifier.java From Refactoring-Bot with MIT License | 5 votes |
/** * Reorder modifiers of a given field or method to comply with the JLS */ @Override public String performRefactoring(BotIssue issue, GitConfiguration gitConfig) throws Exception { String filepath = gitConfig.getRepoFolder() + File.separator + issue.getFilePath(); FileInputStream in = new FileInputStream(filepath); CompilationUnit compilationUnit = LexicalPreservingPrinter.setup(StaticJavaParser.parse(in)); FieldDeclaration field = RefactoringHelper.getFieldDeclarationByLineNumber(issue.getLine(), compilationUnit); MethodDeclaration method = RefactoringHelper.getMethodDeclarationByLineNumber(issue.getLine(), compilationUnit); boolean isModifierListUnchanged = false; NodeList<Modifier> modifiersInCorrectOrder; if (field != null) { modifiersInCorrectOrder = getModifiersInCorrectOrder(field.getModifiers()); isModifierListUnchanged = field.getModifiers().equals(modifiersInCorrectOrder); field.setModifiers(new NodeList<Modifier>()); field.setModifiers(modifiersInCorrectOrder); } else if (method != null) { modifiersInCorrectOrder = getModifiersInCorrectOrder(method.getModifiers()); isModifierListUnchanged = method.getModifiers().equals(modifiersInCorrectOrder); method.setModifiers(new NodeList<Modifier>()); method.setModifiers(modifiersInCorrectOrder); } else { throw new BotRefactoringException("Could not find method or field declaration at the given line!"); } if (isModifierListUnchanged) { throw new BotRefactoringException("All modifiers are in correct order! Nothing to refactor."); } // Save changes to file PrintWriter out = new PrintWriter(filepath); out.println(LexicalPreservingPrinter.print(compilationUnit)); out.close(); // Return commit message return "Reordered modifiers to comply with the Java Language Specification"; }
Example #12
Source File: JavaParsingAtomicQueueGenerator.java From JCTools with Apache License 2.0 | 5 votes |
/** * Generates something like * <code>private static final AtomicLongFieldUpdater<MpmcAtomicArrayQueueProducerIndexField> P_INDEX_UPDATER = AtomicLongFieldUpdater.newUpdater(MpmcAtomicArrayQueueProducerIndexField.class, "producerIndex");</code> * * @param className * @param variableName * @return */ protected FieldDeclaration declareLongFieldUpdater(String className, String variableName) { MethodCallExpr initializer = newAtomicLongFieldUpdater(className, variableName); ClassOrInterfaceType type = simpleParametricType("AtomicLongFieldUpdater", className); FieldDeclaration newField = fieldDeclarationWithInitialiser(type, fieldUpdaterFieldName(variableName), initializer, Keyword.PRIVATE, Keyword.STATIC, Keyword.FINAL); return newField; }
Example #13
Source File: GeneralFixture.java From TestSmellDetector with GNU General Public License v3.0 | 5 votes |
@Override public void visit(ClassOrInterfaceDeclaration n, Void arg) { NodeList<BodyDeclaration<?>> members = n.getMembers(); for (int i = 0; i < members.size(); i++) { if (members.get(i) instanceof MethodDeclaration) { methodDeclaration = (MethodDeclaration) members.get(i); //Get a list of all test methods if (Util.isValidTestMethod(methodDeclaration)) { methodList.add(methodDeclaration); } //Get the setup method if (Util.isValidSetupMethod(methodDeclaration)) { //It should have a body if (methodDeclaration.getBody().isPresent()) { setupMethod = methodDeclaration; } } } //Get all fields in the class if (members.get(i) instanceof FieldDeclaration) { fieldList.add((FieldDeclaration) members.get(i)); } } }
Example #14
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 #15
Source File: RefactoringHelper.java From Refactoring-Bot with MIT License | 5 votes |
/** * Finds a field declaration in a compilation unit that starts at the specified * line number * * @param lineNumber * @param cu * @return FieldDeclaration or null if none found */ public static FieldDeclaration getFieldDeclarationByLineNumber(int lineNumber, CompilationUnit cu) { FieldDeclaration result = null; List<FieldDeclaration> fields = cu.findAll(FieldDeclaration.class); for (FieldDeclaration field : fields) { if (isFieldDeclarationAtLine(field, lineNumber)) { result = field; } } return result; }
Example #16
Source File: GroovydocJavaVisitor.java From groovy with Apache License 2.0 | 5 votes |
@Override public void visit(FieldDeclaration f, Object arg) { String name = f.getVariable(0).getNameAsString(); SimpleGroovyFieldDoc field = new SimpleGroovyFieldDoc(name, currentClassDoc); field.setType(makeType(f.getVariable(0).getType())); setModifiers(f.getModifiers(), field); processAnnotations(field, f); f.getJavadocComment().ifPresent(javadocComment -> field.setRawCommentText(javadocComment.getContent())); currentClassDoc.add(field); super.visit(f, arg); }
Example #17
Source File: JavaClassBuilderImpl.java From chrome-devtools-java-client with Apache License 2.0 | 5 votes |
@Override public void generateGettersAndSetters() { List<FieldDeclaration> fields = declaration.getFields(); for (FieldDeclaration fieldDeclaration : fields) { String fieldName = fieldDeclaration.getVariables().get(0).getNameAsString(); setMethodJavadoc(fieldName, fieldDeclaration.createGetter()); setMethodJavadoc(fieldName, fieldDeclaration.createSetter()); } }
Example #18
Source File: ValidationHelper.java From apigcc with MIT License | 5 votes |
public static List<String> getValidations(ResolvedFieldDeclaration declaredField) { List<String> result = new ArrayList<>(); if (declaredField instanceof JavaParserFieldDeclaration) { FieldDeclaration fieldDeclaration = ((JavaParserFieldDeclaration) declaredField).getWrappedNode(); for (String value : values) { Optional<AnnotationExpr> optional = fieldDeclaration.getAnnotationByName(value); if (optional.isPresent()) { result.add(value); } } } return result; }
Example #19
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 #20
Source File: ReorderModifiersTest.java From Refactoring-Bot with MIT License | 5 votes |
@Test public void testReorderFieldModifiers() throws Exception { // arrange int lineNumber = TestDataClassReorderModifiers.lineNumberOfFieldWithStaticAndFinalInWrongOrder; // act File tempFile = performReorderModifiers(lineNumber); // assert FileInputStream in = new FileInputStream(tempFile); CompilationUnit cu = StaticJavaParser.parse(in); FieldDeclaration fieldDeclarationAfterRefactoring = RefactoringHelper .getFieldDeclarationByLineNumber(lineNumber, cu); assertAllModifiersInCorrectOrder(fieldDeclarationAfterRefactoring.getModifiers()); }
Example #21
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 #22
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 #23
Source File: RefactoringHelperTest.java From Refactoring-Bot with MIT License | 5 votes |
@Test public void testGetFieldDeclarationByLineNumber() throws FileNotFoundException { // arrange FileInputStream in = new FileInputStream(getTestResourcesFile()); CompilationUnit cu = StaticJavaParser.parse(in); int lineNumber = TestDataClassRefactoringHelper.lineNumberOfFieldDeclaration; String expectedFieldAsString = "public static int lineNumberOfFieldDeclaration = " + lineNumber + ";"; // act FieldDeclaration field = RefactoringHelper.getFieldDeclarationByLineNumber(lineNumber, cu); // assert assertThat(field).isNotNull(); assertThat(field.toString()).isEqualTo(expectedFieldAsString); }
Example #24
Source File: CommentHelper.java From apigcc with MIT License | 5 votes |
/** * 解析属性的注释 * @param it * @return */ public static Optional<Comment> getComment(ResolvedFieldDeclaration it) { if (it instanceof JavaParserFieldDeclaration) { FieldDeclaration wrappedNode = ((JavaParserFieldDeclaration) it).getWrappedNode(); return wrappedNode.getComment(); } if (it instanceof JavaParserClassDeclaration) { JavaParserClassDeclaration classDeclaration = (JavaParserClassDeclaration) it; return classDeclaration.getWrappedNode().getComment(); } return Optional.empty(); }
Example #25
Source File: JsonPropertyHelper.java From apigcc with MIT License | 5 votes |
/** * 获取Json 别名 * * @param declaredField * @return */ public static Optional<String> getJsonName(ResolvedFieldDeclaration declaredField) { if (declaredField instanceof JavaParserFieldDeclaration) { FieldDeclaration fieldDeclaration = ((JavaParserFieldDeclaration) declaredField).getWrappedNode(); return OptionalHelper.any( AnnotationHelper.string(fieldDeclaration, ANNOTATION_JSON_PROPERTY, "value"), AnnotationHelper.string(fieldDeclaration, ANNOTATION_JSON_FIELD, "name"), AnnotationHelper.string(fieldDeclaration, ANNOTATION_SERIALIZED_NAME, "value") ); } return Optional.empty(); }
Example #26
Source File: JavaClassBuilderImpl.java From chrome-devtools-java-client with Apache License 2.0 | 5 votes |
/** * Adds annotation to field. * * @param name Field name. Could not be in correct format. * @param annotationName Annotation name. */ @Override public void addFieldAnnotation(String name, String annotationName) { Optional<FieldDeclaration> fieldDeclaration = declaration.getFieldByName(getFieldName(name)); if (fieldDeclaration.isPresent()) { MarkerAnnotationExpr annotationExpr = new MarkerAnnotationExpr(); annotationExpr.setName(annotationName); fieldDeclaration.get().addAnnotation(annotationExpr); importAnnotation(annotationName); } else { throw new RuntimeException("Field " + name + " is not present in current class."); } }
Example #27
Source File: ASTHelper.java From stategen with GNU Affero General Public License v3.0 | 5 votes |
/** * Gets the field map. * * @param node the node * @return the field map */ static Map<String, String> getFieldMap(Node node) { Map<String, String> fieldmap = null; Map<String, FieldDeclaration> fieldDeclarationMap = getBodyDeclarationMap(node, FieldDeclaration.class); if (fieldDeclarationMap != null) { fieldmap = new CaseInsensitiveHashMap<String>(fieldDeclarationMap.size()); for (String oldFieldName : fieldDeclarationMap.keySet()) { fieldmap.put(oldFieldName, oldFieldName); } } return fieldmap; }
Example #28
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 #29
Source File: ModelMetaData.java From kogito-runtimes with Apache License 2.0 | 5 votes |
private FieldDeclaration declareField(String name, String type) { return new FieldDeclaration().addVariable( new VariableDeclarator() .setType(type) .setName(name)) .addModifier(Modifier.Keyword.PRIVATE); }
Example #30
Source File: JavaDocParserVisitor.java From jaxrs-analyzer with Apache License 2.0 | 5 votes |
@Override public void visit(FieldDeclaration field, Void arg) { field.getComment() .filter(Comment::isJavadocComment) .map(this::toJavaDoc) .ifPresent(c -> createFieldComment(c, field)); super.visit(field, arg); }