2

How to create eclipse plugin to auto create the serialization code read/writeExternal on existing code java classes?

Steps needed get the class from active tab (and or info on class field info like one in outline window) and generate code for each field, maybe using reflection will also help.

blackuprise
  • 440
  • 6
  • 26
Amit Sehgal
  • 73
  • 1
  • 4
  • I was wondering the same, all I need is current java class metadata like one in Outline window and it can be done, or just a class that is opened in current tab... – blackuprise Apr 03 '14 at 08:53
  • Look at the Eclipse JDT [AST Parser](http://www.vogella.com/tutorials/EclipseJDT/article.html) – greg-449 Apr 03 '14 at 09:13
  • yep, nice info also found this source code for hashcodeEquals from eclipse: http://grepcode.com/file/repository.grepcode.com/java/eclipse.org/4.3.1/org.eclipse.jdt/ui/3.9.1/org/eclipse/jdt/internal/corext/codemanipulation/GenerateHashCodeEqualsOperation.java – blackuprise Apr 03 '14 at 13:00
  • Is it similar to eclipse `generate getters and setters` ? – andyf Apr 10 '14 at 01:50
  • yes, this code is similar to hashcode and equals and generate getters and setters – blackuprise Apr 15 '14 at 07:52

1 Answers1

0

The easiest way is to build upon org.eclipse.jdt.ui.actions.GenerateMethodAbstractAction that is used by eclipse to implement GenerateToStringAction and GeneateHashCodeEqualsAction.

Basically:

  1. Build a basic sub-class of GenerateMethodAbstractAction
  2. Implement logic that enumerates all the fields / properties etc. you want to process in generateCandidates(). You also need to decide if you recurse into superclass or not.
  3. Implement logic that generates MethodDeclarations for readExternal/writeExternal methods using data collected in step 2.
  4. Wrap generated MethodDeclarations into an IWorkspaceRunnable that applies them as edits (see GenerateToStringOperation) and return it from createOperation(...).
  5. Register your new action to "Source" menu so it can be used

The code required is rather long and involved so it's better to follow the two existing action classes for guidance.

If you choose to put it somewhere else than "Source" menu, you can discover the active editor with

PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor()

See also:

Community
  • 1
  • 1
anttix
  • 7,709
  • 1
  • 24
  • 25