-1

I'm looking for a way to use something similar to #define in Java. I am aware there's no preprocessor there, but I doubt something like that can't be implemented. Ideally I'm looking for a way to translate this C++ code in Java:

#include <cstdio>
#define HelloWorld
#define BEGIN {
#define END }
#define PROGRAM int main()
#define WRITELN(a) puts(a);

PROGRAM HelloWorld

BEGIN
    WRITELN("Hello, World")
END

Before this gets marked as duplicate I want to state that I'm looking for a way for a string constant to be defined before compilation, there are questions on this site about numerical ones, but that's not what I'm looking for. I apparently need to explain again how this question is different. The OP of the question somebody linked is asking whether #define in Java exists, to which the answer is no. What I'm asking is how do I declare string constants which are evaluated before compilation.

And I'm aware as well that the use for this is limited, but nonetheless I don't see why something along the lines of #define NAME Larry can't be useful.

1 Answers1

1

I think I see what you're getting at; you're using #define statements as a way to define your own DSL; that is, you're writing specific statements which the compiler translates into valid syntax.

That's...not entirely possible with Java. The reason for this is Java's compilation approach is relatively set in stone.

There's likely a way around this; the main point of the code is that it has to translate to valid bytecode at some layer. If your intent is to get a DSL-like language, you could consider Groovy or Kotlin, which allow cleaner ways to express what will eventually become valid Java bytecode.

Makoto
  • 104,088
  • 27
  • 192
  • 230