-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?

3
  • 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 Commented Dec 14, 2022 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. Commented Dec 14, 2022 at 17:17
  • I understand, thanks a lot for the reply and tips, I will keep them in mind. Commented Dec 19, 2022 at 11:31

1 Answer 1

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.

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

1 Comment

I saw the interface but I didn't realize that is how you can use them, thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.