-1

I know Java does not have pre-processor, but I struggle to find a way to do this.

I am looking to create macros to improve code readibility, to specify which of the functions or parameters are for input or output specifically. In C, this would be done like this :

#define IN
#define OUT

And these would just be used before the variables and functions. Can I simulate the same behavior in Java?

I did not manage to find a way to do this. The only way I found was including defines in the code and first using the cpp pre-processor to replace them, and then run the java code, but maybe there is a better way of doing this?

IlluSion
  • 11
  • 5
  • 4
    You could use annotations like `@Input` and `@Output`, which you'd define yourself via a `public @interface`. My understanding is you want these merely as markers in the source code, which the annotations would allow some auto-complete. However, you might be served just as well by a comment or structuring your design in a way that inputs/outputs are distinct in some fashion – Rogue Dec 14 '22 at 17:15
  • 1
    This is going to produce very non-idiomatic Java. Rather than taking C's habits and porting them to Java, I'd suggest learning (and getting used to) Java's habits. – yshavit Dec 14 '22 at 17:17
  • I understand, thanks a lot for the reply and tips, I will keep them in mind. – IlluSion Dec 19 '22 at 11:31

1 Answers1

1

Java indeed does not have a pre-processor, and your use case doesn't require that either: you aren't actually preprocessing the code, you just put in some tags that the compiler can ignore.

What you are looking for are "annotations" - you basically want to annotate your code with some nice text that will not affect the compiler.

This basically requires defining some specialized Java types for this using the @interface keyword and then you can use them to write things like:

public void doStuff(@Input invar, @Output outvar) {
...

These annotations can be simply:

@interface Input {}

@interface Output {}

or you can add more features and even use reflection to examine them in runtime.

See the linked documentation above for more details.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Guss
  • 30,470
  • 17
  • 104
  • 128