在Java中产生条件编译时错误

时间:2020-03-06 14:19:34  来源:igfitidea点击:

我并不是说编译错误,因为我犯了语法错误或者其他错误。在C ++中,我们可以根据条件创建编译时错误,如下例所示:

template<int> struct CompileTimeError;
template<> struct CompileTimeError<true> {};

#define STATIC_CHECK(expr, msg) { CompileTimeError<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg; }

int main(int argc, char* argv[])
{
    STATIC_CHECK(false, Compile_Time_Failure);
    return 0;
}

在VS 2005中,它将输出:

------ Build started: Project: Test, Configuration: Debug Win32 ------
Compiling...
Test.cpp
f:\temp\test\test\test.cpp(17) : error C2079: 'ERROR_Compile_Time_Failure' uses undefined struct 'CompileTimeError<__formal>'
        with
        [
            __formal=0
        ]
Build log was saved at "file://f:\temp\Test\Test\Debug\BuildLog.htm"
Test - 1 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

有什么办法可以用Java实现呢?

解决方案

如果不使用单独的工具,则无法基于Java中的编译时逻辑来产生任何操作。从技术上讲,可以在Java上使用C预处理程序,但是我们必须注意其有关基础语言的内置假设。如果我是我们,那么我将找到一种更好的方法来完成我们要与此编译时错误一起执行的操作。如果确实有必要,我们甚至可以编写自己的预处理器(可能使用APT)。

用Java无法做到这一点,而不能用它在C ++中为我们服务的方式相同。

我们可能使用注释,并在编译之前或者之后运行apt来检查注释。

例如:

@MyStaticCheck(false, "Compile Time Error, kind-of")
public static void main(String[] args) {
    return;
}

然后编写我们自己的AnnotationProcessorFactory,以查找@MyStaticCheck批注,并对参数进行处理。

注意:我对apt的玩法还不多,但是文档使它看起来非常可行。

正如马特·奎尔(Matt Quail)上面回答的那样,注释与XDoclet一起适合满足需求。这种组合允许进行大量的预处理,代码生成等。