You can但是你不应该.
The 不应该 part:
You 不应该因为以这种方式使用预处理器被认为是不好的做法 https://stackoverflow.com/questions/14041453/why-are-preprocessor-macros-evil-and-what-are-the-alternatives首先,有更好、更惯用的 Java 方法来解决这个用例。
The can部分: (*)
Java本身不支持宏。另一方面,您可以通过管道传输源代码C预处理器 http://en.wikipedia.org/wiki/C_preprocessor(简称CPP)就像C/C++编译链一样。
这是一个演示:
src/Test.java
:
#define READINT (new java.util.Scanner(System.in).nextInt())
class Test {
public static void main(String[] args) {
int i = READINT;
}
}
cpp
命令:
$ 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
更好的解决方法:
您可以使用静态方法编写自己的实用程序类:
import java.util.Scanner;
class StdinUtil {
public final static Scanner STDIN = new Scanner(System.in);
public static int readInt() {
return STDIN.nextInt();
}
}
当你想使用它时,你可以静态导入readInt
method:
import static StdinUtil.readInt;
class Test {
public static void main(String[] args) {
int i = readInt();
}
}
(or do static import StdinUtil.STDIN;
并使用STDIN.nextInt()
.)
最后,讲一个轶事
我自己曾经在Java代码上使用过CPP预处理方法!我正在为一门课程创建一个编程作业。我希望能够轻松地从参考解决方案中提取代码框架。所以我只用了几个#ifdef
过滤掉解决方案中的“秘密”部分。这样我就可以维护参考解决方案,并轻松地重新生成代码框架。
这篇文章已被重写为一篇文章here http://programming.guide/java/macros-in-java-source-files.html.
(*) Since I hate answering questions with "you shouldn't". Besides, some future reader may have good reasons for wanting to use the cpp
in conjunction with Java sources!