1

I am trying to read some .java files using a java code. What I am trying is to find the beginning of all the java methods defined in the .java file.

Any regular expression or any other solution to parse a java file to achieve that?

Vivek Singh
  • 2,047
  • 11
  • 24
Vik
  • 8,721
  • 27
  • 83
  • 168
  • 6
    Do yourself a favor. Compile those java files, create .class files load those classes and use reflection to get method names. Regex was never meant for stuff like this – TheLostMind Nov 03 '15 at 05:01
  • thanks but i need to do more then just finding those method names etc. i actually need to do some code modification in the beginning of those methods. – Vik Nov 03 '15 at 05:10
  • A text parser will help you. But I strongly suggest steering clear from that approach. – TheLostMind Nov 03 '15 at 05:22
  • well if i have to modify the source code based on first searching the methods then what else would you recommend? if i only needed the method names then your suggestion makes a lot of sense to use compiled code. any advise please – Vik Nov 03 '15 at 05:28
  • In that case you will probably have to go with the answer below. Make sure you test all cases – TheLostMind Nov 03 '15 at 05:30

1 Answers1

0

If you just simply want to extract information, easiest solution would be to compile the target code, and then use reflection to get the names of the methods, etc., like Vinod mentions in the comment above.

If your aim is to modify the actual sources in some way before compilation, or something to that effect, I suppose you are stuck parsing the source text.

A discussion of some lengthy and truly grotesque regular expressions to accomplish method signature matching is discussed here: Regex that Will Match a Java Method Declaration

Jameson
  • 6,400
  • 6
  • 32
  • 53
  • i need to do more in the source file itself and so compiling is not a very good solution for me. – Vik Nov 03 '15 at 05:11