Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
kanran2024
@kanran2024
can this parser be used to provide content assist for the java language?
devfat
@devfat
Can javaparser be used to modify pom.xml? Such as update dependencies version
Björn Kautler
@Vampire
How should it? JavaParser is for parsing and generating Java code. pom.xml is XML.
Ayush
@Ayush-D

Can I find all the occurrence of an object using JavaParser? How can I filter this information in AST?

Example:

Class A = null;
if (A.someMethod() ) {
... do something
}
if (B.someMethod() ) {
... do something
}
if (A.someOtherMethod() ) {
... do something
}

So we should get A object is used in 2 places. {additional} can we get line numbers also?

4 replies
Udo Borkowski
@abego

I see in JavaParserClassDeclaration this code:

    @Deprecated
    @Override
    public SymbolReference<TypeDeclaration> solveType(String name, TypeSolver typeSolver) {...}

If this method solveType is deprecated what is the suggested alternative?

1 reply
Karthi G
@karthi_:matrix.org
[m]

Hi Team,

I am currently trying a serialize and de-serialize node to write and read from file. Once I de-serialize the node when I call findCompilationUnit() api it returns empty.
Is there a way to get the compilation unit of the node after deserialization?
Also let me know if there is a option to serialize and de-serialize node without losing its compilation unit?

3 replies
Zueyjajie
@Zueyjajie
Hi, could you please tell me, is Java parser requires jdk or only jre?
1 reply
Chinese News Board
@ralphcnb_twitter

This has happened a few times before, and I just go ahead and change it, but I THINK (not sure) this is a bug. Java seems to have no problems (neither compiler-errors, nor warnings) about private methods in an interface... JavaParser always complains about it, though...

The Line where it says 'private' is not allowed here. is complaining about a private method in an interface. It has
done this several times in the past few years, and I always just go and make it something like default

Upgrading File: javadoc/Torello/HTML/Tools/JavaDoc/HiLiter.html
Processing File: [Torello/HTML/Tools/JavaDoc/HiLiter.java], (Java Source Code File):
    Processor [MainFilesProcessor], Fatal Error:  Exception Thrown:
    ************************************************************************
    THROWN: com.github.javaparser.ParseProblemException
    Throwable.getMessage():
        (line 153,col 5) 'private' is not allowed here.

    StackTrace:
        260:  com.github.javaparser.StaticJavaParser.handleResult()
        229:  com.github.javaparser.StaticJavaParser.parse()
        110:  Torello.HTML.Tools.JavaDoc.JavaSourceCodeFile.HATRED()
        172:  Torello.HTML.Tools.JavaDoc.JavaSourceCodeFile.<init>()
        603:  Torello.HTML.Tools.JavaDoc.MainFilesProcessor.run()
        318:  Torello.HTML.Tools.JavaDoc.MainFilesProcessor.runAll()
        1163: Torello.HTML.Tools.JavaDoc.Upgrade.upgrade()
        107:  Torello.Build.Stages.S03Upgrade.upgrade()
        70:   Torello.Build.Build.main()
8 replies
Udo Borkowski
@abego

I am currently working on a large software migration project and verify the quality of the generated Java code with some tools that are using JavaParser. While writing the actual checks with JavaParser was quite easy it turned out performance was the real problem. Processing the code base (more than 20 000 classes) took several hours to complete.

By profiling my applications I identified several places in the current JavaParser code that affect the performance and memory usage. And I came up with some solutions that sped up the runtime significantly. E.g. with three little changes I was able to reduce the time for one tool run from more than 2 hours to less than 15 minutes.

I published my enhancements to the JavaParser code and created pull requests.

Let me know what you think,

Udo

(javaparser/javaparser#3655 javaparser/javaparser#3656 javaparser/javaparser#3657 javaparser/javaparser#3658 )

3 replies
Saif Ur Rahman
@saifsmailbox98
Hi
Is the JavaParser: Visited ebook freely available?
(without the membership fee)
1 reply
Björn Kautler
@Vampire
What membership fee? You pay a one-time price and you can freely choose the amount, so choose 0 if you don't want to reward the authors.
Satrio Adi Rukmono
@rsatrioadi

Hello,

I'm doing program analysis that involves finding method calls (A calls method(s) of B) and field accesses (A accesses field(s) of B). For method calls I simply visit A's MethodCallExpr and call resolve().declaringType() and check if the type equals B. However I cannot find the equivalent for field accesses. Can anyone help me with this?

Thank you in advance.

14 replies
Chinese News Board
@ralphcnb_twitter
I mean, I said quite a few times already, I don't do The Linker (Symbol-Solver)... So the last step where there is an invocation of resolve(), I cannot help you, but, I assume you already know how to do this?
public static void printFieldAccesses(String classFileName) throws Exception
{
    String          classAsStr  = FileRW.loadFileToString(classFileName);
    CompilationUnit cu          = StaticJavaParser.parse(classAsStr);
    boolean         evenOdd     = true;

    System.out.println(classFileName + " accesses:");

    for (FieldAccessExpr fae : cu.findAll(FieldAccessExpr.class))

        System.out.print
            (((evenOdd = ! evenOdd) ? C.BGREEN : C.BRED) + fae.toString() + C.RESET + ", ");
}
Chinese News Board
@ralphcnb_twitter
tjava.png
Chinese News Board
@ralphcnb_twitter

I guess @matozoid quit? Danny van Bruggen left Java Parser? That what it says on his page... Anyway, if (maybe) @jlerbsc or anybody happens to know this one... I just want to know if all this is really necessary? If I have any old TypeDeclaration can I retrieve a String that includes everything on the line?

For instance, I am retrieving:
public static class MyInnerClass<T extends HTMLNode>

Is there any BodyDeclaration.getSignature() or something like that? I really couldn't find one... The posted-below-code works fine, but I was just wondering if there were a 'one-line-er' in that big list of getters in TypeDeclaration to get a signature or declaration for a type?

private static String signatureBuilder(TypeDeclaration<?> td)
{
    StringBuilder sb = new StringBuilder();

    for (Modifier m : td.getModifiers()) sb.append(m.toString().trim() + ' ');

    sb.append(td.getNameAsString());

    if (td.isClassOrInterfaceDeclaration())
    {
        boolean first = true;

        for (TypeParameter tp : td.asClassOrInterfaceDeclaration().getTypeParameters())
        {
            if (first)  { sb.append('<'); first=false; }
            else        sb.append(", ");

            sb.append(tp.toString());
        }

        if (! first) sb.append('>');
    }

    return sb.toString();
}
movhome
@movhome
android.content.res.Resources$NotFoundException
5 replies
cannot resolve
movhome
@movhome
Exception in thread "main" UnsolvedSymbolException{context='null', name='android.content.res.Resources$NotFoundException', cause='null'}
at com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver.solveType(CombinedTypeSolver.java:189)
at com.github.javaparser.symbolsolver.javassistmodel.JavassistMethodLikeDeclarationAdapter.getSpecifiedException(JavassistMethodLikeDeclarationAdapter.java:113)
at com.github.javaparser.symbolsolver.javassistmodel.JavassistMethodDeclaration.getSpecifiedException(JavassistMethodDeclaration.java:144)
at com.github.javaparser.resolution.MethodUsage.<init>(MethodUsage.java:54)
at com.github.javaparser.symbolsolver.javassistmodel.JavassistUtils.solveMethodAsUsage(JavassistUtils.java:78)
at com.github.javaparser.symbolsolver.javassistmodel.JavassistClassDeclaration.solveMethodAsUsage(JavassistClassDeclaration.java:131)
at com.github.javaparser.symbolsolver.javaparsermodel.contexts.ContextHelper.solveMethodAsUsage(ContextHelper.java:48)
at com.github.javaparser.symbolsolver.javaparsermodel.contexts.MethodCallExprContext.solveMethodAsUsage(MethodCallExprContext.java:197)
at com.github.javaparser.symbolsolver.javaparsermodel.contexts.MethodCallExprContext.solveMethodAsUsage(MethodCallExprContext.java:467)
at com.github.javaparser.symbolsolver.javaparsermodel.contexts.MethodCallExprContext.solveMethodAsUsage(MethodCallExprContext.java:138)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.solveMethodAsUsage(JavaParserFacade.java:815)
at com.github.javaparser.symbolsolver.javaparsermodel.TypeExtractor.visit(TypeExtractor.java:329)
at com.github.javaparser.symbolsolver.javaparsermodel.TypeExtractor.visit(TypeExtractor.java:71)
at com.github.javaparser.ast.expr.MethodCallExpr.accept(MethodCallExpr.java:116)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.getTypeConcrete(JavaParserFacade.java:547)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.getType(JavaParserFacade.java:394)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.solveArguments(JavaParserFacade.java:296)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.solve(JavaParserFacade.java:315)
at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.solve(JavaParserFacade.java:179)
at com.github.javaparser.symbolsolver.JavaSymbolSolver.resolveDeclaration(JavaSymbolSolver.java:161)
at com.github.javaparser.ast.expr.MethodCallExpr.resolve(MethodCallExpr.java:317)
movhome
@movhome
BUG REPORT: if a class implements an inner-interface like "c.i", the class "c" extend "d", the "i" interface is an inner type of "d", then, the class can not be resolved too
Chinese News Board
@ralphcnb_twitter
My Java Doc Broken LinksChecker was just added (by me)! It checks every relative-link on a Java Doc Page... I also now have native-Java-Parser hooks to MethodDeclaration, ConstructorDeclaration, etc.. with all of my Reflection -> Java Doc HTML Upgrader Classes (Java HTML)
Ayush
@Ayush-D

Hey Members,
If we have a line number in the Java code having null obj, then how can I add a condition for Non-null object Object.nonNull(obj) before that line using JP?

Example

try{
  ....< We have null object obj>
}
catch (NPE e){
....
}

Then it should add a condition handling null object like this:

try{
  if(Objects.nonNull(obj) {
  ....< We have null object obj>
  }
}
catch (NPE e){
....
}

How if(Objects.nonNull(obj) { can be added before that block of code

6 replies
Chinese News Board
@ralphcnb_twitter
Anybody in Java Parser World do stuff with this from javax? javax.lang.model.ElementVisitor - and its Adapters (of which there are many)?
Udo Borkowski
@abego

JavaParser version 3.24.6 was released nearly two weeks ago (2022-08-26). However when I change my pom to use that version I get the error:

Could not find artifact com.github.javaparser:javaparser-symbol-solver-core:pom:3.24.6 in secure-central (https://repo1.maven.org/maven2/)

How long will it take until I can get the latest version via Maven Central?

Udo Borkowski
@abego

I think something went wrong in the release process of 3.24.6. There is a major difference in the commit sequence for release 3.24.4 and 3.24.6.

For 3.24.4 we had these commits (beside others):

  • [maven-release-plugin] update readme
  • [maven-release-plugin] prepare release javaparser-parent-3.24.4 (with tag javaparser-parent-3.24.4)
  • [maven-release-plugin] prepare for next development iteration

For 3.24.6. it looks like this:

  • [maven-release-plugin] update readme (with tag javaparser-parent-3.24.6)
  • [maven-release-plugin] prepare for next development iteration

As you can see the step prepare release javaparser-parent-3.24.6 is missing and the tag is at the wrong (too early) commit. That commit still has poms with <version>3.24.6-SNAPSHOT</version>.

Actually I found no commit that has a <version>3.24.6</version> in any pom, necessary for the release of 3.24.6.

7 replies
Robin Francis
@strawHatRobby
leanpub based book is no longer free. Its asking me to join by paying dollar 20, not so much open source if I have to pay for the documentation itself :(
2 replies
Sebastiaan de Schaetzen
@seeseemelk
Is the book available somewhere else where it is not available "for free" behind a paywall?
Raphael Jenni
@RaphaelJenni
Same as for the two comments above, I'd like to see the documentation without having to pay for it. I'm happy to pay for it as soon as it has proven itself for being worth it and I continue using the javaparser lib. Please remove the paywall.
seroze
@seroze
hi, can we use javaparser for style checker
2 replies
Ethan Keller
@eak24
Hello, I'm trying to do some very specific whitespace cleaning in my Java codebase and I'd like to delete whitespace surrounding a node. But when I run myNode.getTokenRange().get().getEnd().deleteToken() that doesn't seem to impact the final printed result. What is the proper way to delete tokens? I looked at the result from using the PrettyPrinter and the LexicalPreservingPrinter. It seems like deleteToken just doesn't impact the AST at all. Is that the case?
4 replies
Yuxiang Wei
@UniverseFly
Hi, does anyone know if javaparser supports parsing partial programs (i.e., incomplete code)?
1 reply
Smurfy98
@Smurfy98
Hi, is there some resource that showcases how to acquire all types used in a compilation unit? I am trying to somehow adapt the VoidVisitor example but there is no method visit(Type n, A arg). I don't want to get all defined types in that file, I really mean all used ones. So variables, method arguments etc. I was hoping there was a simpler solution then writing visit overrides for everything that could contain a type.
10 replies
ylq2250
@ylq2250
Hi,does anyone knows that javaparser seems like not work very well with lombok,when I annotate a class with '@Slf4j' and use 'log.info("ok")',I get an Exception:
Exception in thread "main" UnsolvedSymbolException{context='log.info("ok")', name='log', cause='UnsolvedSymbolException{context='log', name='Solving log', cause='null'}'}
at com.github.javaparser.symbolsolver.javaparsermodel.contexts.AbstractJavaParserContext.findTypeDeclarations(AbstractJavaParserContext.java:222)
I wonder how to solve this problem,The question stuck me.
2 replies
huankai
@minkai95
Hi,I got a ClassOrInterfaceDeclaration Object, now i want to get a method from AnonymousClassBody in ClassOrInterfaceDeclaration Object.
I don't know use other api got it.Who can tell me? thank u. If you can show me your code example that It's for the best.
2 replies
Jonathan Locke
@jonathanl-telenav
Hello All, I'm using javaparser in Lexakai (https://www.lexakai.org) to generate/update markdown and UML diagrams. Is there an effort in progress to update javaparser to Java 17 yet? Thanks. -- Jon
Jonathan Locke
@jonathanl-telenav
I see this in the code, and I'm wondering if we could simply have a flag not to throw the exception (I don't need to access the parse tree for java 17 switch statements):
    final Validator noPatternMatchingInstanceOf = new SimpleValidator<>(InstanceOfExpr.class,
            n -> n.getPattern().isPresent(),
            (n, reporter) -> reporter.report(n, "Use of patterns with instanceof is not supported.")
    );
Or maybe there's a way to configure the reporter here?
Jonathan Locke
@jonathanl-telenav
AHHH. I found it... setLanguageLevel. BRAVO!
1 reply
Nakhla Rafi
@nakhlarafi
Hello, Can anyone help me with any article or link where I can learn how to use Java parser to generate AST in java source code?
1 reply
Umang
@umangdd_twitter

Trying to generate if statement something like this
if(isValid()) {
}

guessing use of IfStmt with BinaryExpression is there good example around this

4 replies
geajack
@geajack
Hey there, is the book still intended to be free? LearnPub seems to want you to sign up for a (paid) account for it.
2 replies
Mohammad Eglil
@MohammadEglil

Hello everybody,
Did anybody encountered the following exception:

java.lang.NoClassDefFoundError: Could not initialize class com.github.javaparser.ParseStart

Mohammad Eglil
@MohammadEglil
On my local machine with java 11 everything worked fine but unfortunately on the remote machine it does not work
the remote machine has java 8 and i am using javaparser-core-3.24.4.jar
5 replies
jean pierre Lerbscher
@jlerbsc
javaparser 3.24.8 has just been released.
Mohammad Eglil
@MohammadEglil
Hello everybody,
Its me again but hopefully this time with a real issue:
Does anybody know whether the lexicalpreservingprinter keeps preserving of comments?
Mohammad Eglil
@MohammadEglil
I had a look at the code and it does not look like it would unfortunately...so another question: is there a possibility to get all comments along with the commented node?
2 replies
Udo Borkowski
@abego

The LexicalPreservingPrinter does preserve whitespaces and comments from the "original" Java code.

When you want to dive deeper into the whitespace/comment handling I suggest you check out the "JavaParser Visited" book or have a look at the JavaParser source code and look for NodeText and how it is used, e.g. in LexicalPreservingPrinter.prettyPrintingTextNode(...).

9 replies