-1

I am working on a module where I have to convert a set of logical representations and other data into Java source code.

I would like to be able to first convert them to an intermediary representation of Java elements (classes, methods, etc), and then convert this intermediary representation to an actual String/textfile.

for example, I would like to just be able to construct an element like this:

JavaClass myClass = new JavaClass("MyClass", "MyParent", new String[] {"MyInterface", "MySecondInterface"}); 

and then have the toString() method of myClass output something like:

class MyClass extends MyParent implements MyInterface, MySecondInterface { } 

and so on and so forth for variables, methods, statements etc - preferably with formatting. The example is oversimplified just for the sake of demonstration - in reality I would prefer a representation that at least resembles an abstract syntax tree.

I have looked at the com.sun.org.apache.bcel.* package, but since it is meant for bytecode it does not help much here. Transformation frameworks (such as Recoder) also do not seem to be what I am looking for.

Can anyone recommend a framework I can use for this?

1
  • Closed as off topic after 12 years? Well done SO. Commented Nov 11, 2024 at 9:49

2 Answers 2

1

You could use a template engine like freemarker. Write a 'class' template and use freemarker to put in your data. Really simple to use. Freemarker support everything you need like interation, conditions, ...

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this comes closest to what I was looking for. I have opted to use StringTemplate instead of FreeMarker, but I will accept your answer since you pointed me to the correct catergory of software.
1

You should look into Javassist. It has a really simple API for creating classes on the fly.

3 Comments

Thanks, but the crucial requirement is that I can convert the representation to a Java source file (see my primitive example in the OP). This framework, unless I am missing something, only deals in bytecode, much like Apache BCEL.
@chrsv I don't know how well it works, but you might try this with Javassist: fuin.org/srcgen4javassist/examples.html
Thanks, unfortunately this solution becomes a bit inflexible and awkward for what I am trying to do in the end. I found that using a template engine is more or less precisely what I need. Thanks anyway!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.