Two Laptop Bag
The moose likes Beginning Java and the fly likes Parsing a .java file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Parsing a .java file" Watch "Parsing a .java file" New topic

Parsing a .java file

Em Aiy
Ranch Hand

Joined: May 11, 2006
Posts: 226
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?

    The difference between <b>failure</b> and <b>success</b> is often being <b>right</b> and being <b>exactly right</b>.
    Jeanne Boyarsky
    author & internet detective

    Joined: May 26, 2003
    Posts: 33107

    An open source project like PMD reads in Java code very robustly. You could see how they do it.

    [OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
    Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
    David Newton

    Joined: Sep 29, 2008
    Posts: 12617

    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.
    I agree. Here's the link:
    subject: Parsing a .java file
    It's not a secret anymore!