Posts

Showing posts with the label Macros

Can I Have Macros In Java Source Files

Answer : You can but you shouldn't . The shouldn't part: You shouldn't because using the pre-processor in that way is considered bad practice to start with, and there are better and more Java-idiomatic ways to solve this use case. The can part: (*) Java itself doesn't support macros. On the other hand, you could pipe the source code through the C pre processor (CPP for short) just like the C/C++ compile chain does. Here's a demo: src/Test.java : #define READINT (new java.util.Scanner(System.in).nextInt()) class Test { public static void main(String[] args) { int i = READINT; } } cpp command: $ cpp -P src/Test.java preprocessed/Test.java Result: class Test { public static void main(String[] args) { int i = (new java.util.Scanner(System.in).nextInt()); } } Compile: $ javac preprocessed/Test.java A better workaround: You can write your own utility class with a static method instead: import ja...