• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Parsing a .java file

 
Em Aiy
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have this piece of code (it's a sample)



What i need to do is to read this file as input and write an xml output file. which in this case would be


--------------------------------------------------------------------------------------------------------
Now, i have parsed and did the required job but i am not satisified with the implementation. I have read via InputReader and then match the hardcoded String to get the class name i.e there should be "class" keyword and "{" in the line and if it is true then i find the "className" in it. Now, what if the user has written the code as

My code will not get it's class name and hence will fail all over.

Now, what I was thinking
  • is there any api which reads the Java Files to get us better understanding? I was thinking about reflection API but in that case, i would not be able to read the lines which are in the fieldList array.
  • The second option could be using "Regular Expression". But i guess that would be more complex then


  • What should i do, any suggestions?

     
    Jeanne Boyarsky
    author & internet detective
    Marshal
    Posts: 34965
    378
    Eclipse IDE Java VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Muhammad,
    An open source project like PMD reads in Java code very robustly. You could see how they do it.
     
    David Newton
    Author
    Rancher
    Posts: 12617
    IntelliJ IDE Ruby
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Your requirements are too vague to help effectively.

    Your XML file contains only the elements in the fieldList array; creating XML from that is trivial and doesn't require any parsing at all-it just requires the ability to traverse the fieldList array and produce a suitable XML element for each type contained in the list.

    If you *do* need to actually parse the Java file then use something like Antler or JavaCC or something, which are actual parsers. Unless your parsing needs are simplistic ("look for the fieldList value and grab everything in the following block) you do *not* want to parse Java by hand.

    If you can be more specific regarding your actual needs and the conditions under which you must operate it'd be easier to provide input.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic