如何让java编译器将变量名称插入到字符串中

Edu*_*rch 5 java compiler-construction

我经常发现自己编写这样的代码:

throwExceptionWhenEmpty(fileType, "fileType");
throwExceptionWhenEmpty(channel, "channel");
throwExceptionWhenEmpty(url, "url");
Run Code Online (Sandbox Code Playgroud)

throwExceptionWhenEmpty方法执行以下操作:

private void throwExceptionWhenEmpty(final String var, final String varName) {
    if (var == null || var.isEmpty()) {
        throw new RuntimeException("Parameter " + varName + " may not be null or empty.");
    }
}
Run Code Online (Sandbox Code Playgroud)

我想避免这种明显的冗余将变量名称作为字符串传递.有没有一种方法java编译器可以为我插入字符串中的变量名称?

如果我能写出这样的东西,我会很高兴的:

throwExceptionWhenEmpty(fileType, nameOf(fileType));
Run Code Online (Sandbox Code Playgroud)

Chr*_*bek 2

不,Java 不能做到这一点,直到它开始支持闭包,使字段(和方法)成为编程语言的一等公民。

有关其中一项提案的概述,请参阅http://docs.google.com/Doc?id=ddhp95vd_6hg3qhc#field ,您可以在其中使用语法执行您想要的操作。