简体   繁体   English

模拟C/C++空定义Java

[英]Simulating C/C++ empty defines in Java

I know Java does not have pre-processor, but I struggle to find a way to do this.我知道 Java 没有预处理器,但我很难找到一种方法来做到这一点。

I am looking to create macros to improve code readibility, to specify which of the functions or parameters are for input or output specifically.我正在寻找创建宏以提高代码可读性,以指定哪些函数或参数用于输入或具体为 output。 In C, this would be done like this:在 C 中,这将像这样完成:

#define IN
#define OUT

And these would just be used before the variables and functions.这些只会在变量和函数之前使用。 Can I simulate the same behavior in Java?我可以在 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?我发现的唯一方法是在代码中包含定义并首先使用 cpp 预处理器替换它们,然后运行 java 代码,但也许有更好的方法来做到这一点?

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. Java 确实没有预处理器,您的用例也不需要:您实际上并没有预处理代码,您只是放入了一些编译器可以忽略的标签。

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:这基本上需要使用@interface关键字为此定义一些专门的 Java 类型,然后您可以使用它们来编写如下内容:

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.有关更多详细信息,请参阅上面的链接文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM