0

I would like to manipulate Java classes (with java extension not .class) so that I could :

  • Delete all methods of a class (keeping the constructor)

  • Add unimplemented methods

  • Remove unused imports

  • ...

Is there an API that could accomplish this ?

What I've done so far is trying to manipulate the .java files like text files (with regex,FileUtils, etc.).

Regards. I

Patty
  • 13
  • 1

4 Answers4

1

You could look at using the AST (Abstract Syntax Tree) tools from the Eclipse JDT project.

There is a tutorial to get you started at Vogella: Eclipse JDT - Abstract Syntax Tree (AST) and the Java Model - Tutorial

tonys
  • 3,855
  • 33
  • 39
0

If you only want to temporarily modify the classes (i.e. within the scope of the jvm) then you could do this with reflection:

What is reflection and why is it useful?

If you're taking about permanently altering/creating source code then this is maybe best done using an IDE. Most IDE will tell you about unimplemented methods and provide auto completion to create them. They will also format the source code, remove unused imports etc.

Community
  • 1
  • 1
robjwilkins
  • 5,462
  • 5
  • 43
  • 59
  • Reflection would not be helpful. As stated : I want to manipulate ".java" files not compiled classes. I want to avoid using IDEs as my intention is to put in place scripts that do that job. Then, I have thousands of classes to alter. – Patty Jul 16 '15 at 11:02
  • 1
    I think your best bet would be to do it in an IDE then. Eclipse, Intelij etc will do this easily – robjwilkins Jul 16 '15 at 11:03
  • I know :) But doing with a script would be better ;) – Patty Jul 16 '15 at 11:04
0

Yes, you can use java reflection api. Please check here

Later edit: To update the class structure you can use javassist. Here you have an example.

Community
  • 1
  • 1
Daniel Boncioaga
  • 336
  • 1
  • 13
0

You can use a regular expression, the question then is then what regular expression (And what other options are there!)

Regular expressions maybe aren't ideally suited to this, and for example, when it comes to another task they're not ideally suited to, such as parsing XML, people say don't do it, use an XML parser, but in this case, if you find that there is an absence of a tool built for parsing java source code, then regular expressions may be the best option.

barlop
  • 12,887
  • 8
  • 80
  • 109