Java中的#define

发布于 2024-08-15 20:56:52 字数 213 浏览 3 评论 0原文

我开始用 Java 编程,我想知道是否存在与 C++ #define 等效的东西。

谷歌的快速搜索表明它不存在,但有人可以告诉我是否存在类似的东西 在Java中? 我正在努力使我的代码更具可读性。

我希望能够编写 myArray[PROTEINS] 而不是 myArray[0]例子。

I'm beginning to program in Java and I'm wondering if the equivalent to the C++ #define exists.

A quick search of google says that it doesn't, but could anyone tell me if something similar exists
in Java? I'm trying to make my code more readable.

Instead of myArray[0] I want to be able to write myArray[PROTEINS] for example.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

你是暖光i 2024-08-22 20:56:52

不,因为没有预编译器。但是,在您的情况下,您可以实现相同的效果,如下所示:

class MyClass
{
    private static final int PROTEINS = 0;

    ...

    MyArray[] foo = new MyArray[PROTEINS];

}

编译器会注意到 PROTEINS 永远不会改变,因此将内联它,这或多或少是您想要的。

请注意,常量的访问修饰符在这里并不重要,因此如果您想在多个类中重用同一常量,则可以将其设置为 publicprotected 而不是 private。

No, because there's no precompiler. However, in your case you could achieve the same thing as follows:

class MyClass
{
    private static final int PROTEINS = 0;

    ...

    MyArray[] foo = new MyArray[PROTEINS];

}

The compiler will notice that PROTEINS can never, ever change and so will inline it, which is more or less what you want.

Note that the access modifier on the constant is unimportant here, so it could be public or protected instead of private, if you wanted to reuse the same constant across multiple classes.

再浓的妆也掩不了殇 2024-08-22 20:56:52

注释空间太小,所以这里为您提供一些有关 static final 使用的更多信息。正如我在对 Andrzej 的答案的评论中所说,只有原始和 String 作为文字直接编译到代码中。为了演示这一点,请尝试以下操作:

您可以通过创建三个类(在单独的文件中)来查看其实际效果:

public class DisplayValue {
    private String value;

    public DisplayValue(String value) {
        this.value = value;
    }

    public String toString() {
        return value;
    }
}

public class Constants {
    public static final int INT_VALUE = 0;
    public static final DisplayValue VALUE = new DisplayValue("A");
}

public class Test {
    public static void main(String[] args) {
        System.out.println("Int   = " + Constants.INT_VALUE);
        System.out.println("Value = " + Constants.VALUE);
    }
}

编译这些类并运行测试,它会打印:

Int    = 0
Value  = A

现在,将 Constants 更改为具有不同的值每个都只编译类Constants。当您再次执行 Test 时(无需重新编译类文件),它仍然会打印 INT_VALUE 的旧值,但不会打印 VALUE。例如:

public class Constants {
    public static final int INT_VALUE = 2;
    public static final DisplayValue VALUE = new DisplayValue("X");
}

运行测试而不重新编译 Test.java

Int    = 0
Value  = X

请注意,与 static final 一起使用的任何其他类型都将保留作为引用。

类似于 C/C++ #if/#endif,常量文字或通过带有原语的 static final 定义的常量文字,用于常规 Java < code>if 条件并计算为 false 将导致编译器剥离 if 块中语句的字节码(它们不会生成)。

private static final boolean DEBUG = false;

if (DEBUG) {
    ...code here...
}

“...code here...”处的代码不会被编译为字节码。但如果您将 DEBUG 更改为 true 那么它就会。

Comment space too small, so here is some more information for you on the use of static final. As I said in my comment to the Andrzej's answer, only primitive and String are compiled directly into the code as literals. To demonstrate this, try the following:

You can see this in action by creating three classes (in separate files):

public class DisplayValue {
    private String value;

    public DisplayValue(String value) {
        this.value = value;
    }

    public String toString() {
        return value;
    }
}

public class Constants {
    public static final int INT_VALUE = 0;
    public static final DisplayValue VALUE = new DisplayValue("A");
}

public class Test {
    public static void main(String[] args) {
        System.out.println("Int   = " + Constants.INT_VALUE);
        System.out.println("Value = " + Constants.VALUE);
    }
}

Compile these and run Test, which prints:

Int    = 0
Value  = A

Now, change Constants to have a different value for each and just compile class Constants. When you execute Test again (without recompiling the class file) it still prints the old value for INT_VALUE but not VALUE. For example:

public class Constants {
    public static final int INT_VALUE = 2;
    public static final DisplayValue VALUE = new DisplayValue("X");
}

Run Test without recompiling Test.java:

Int    = 0
Value  = X

Note that any other type used with static final is kept as a reference.

Similar to C/C++ #if/#endif, a constant literal or one defined through static final with primitives, used in a regular Java if condition and evaluates to false will cause the compiler to strip the byte code for the statements within the if block (they will not be generated).

private static final boolean DEBUG = false;

if (DEBUG) {
    ...code here...
}

The code at "...code here..." would not be compiled into the byte code. But if you changed DEBUG to true then it would be.

吾家有女初长成 2024-08-22 20:56:52
static final int PROTEINS = 1
...
myArray[PROTEINS]

通常,您会将“常量”放入类本身中。请注意,编译器可以优化对其的引用,因此除非重新编译所有使用的类,否则不要更改它。

class Foo {
  public static final int SIZE = 5;

  public static int[] arr = new int[SIZE];
}
class Bar {
  int last = arr[Foo.SIZE - 1]; 
}

编辑周期...SIZE=4。同时编译 Bar 因为你的编译器可能刚刚在最后一个编译周期写入了“4”!

static final int PROTEINS = 1
...
myArray[PROTEINS]

You'd normally put "constants" in the class itself. And do note that a compiler is allowed to optimize references to it away, so don't change it unless you recompile all the using classes.

class Foo {
  public static final int SIZE = 5;

  public static int[] arr = new int[SIZE];
}
class Bar {
  int last = arr[Foo.SIZE - 1]; 
}

Edit cycle... SIZE=4. Also compile Bar because you compiler may have just written "4" in the last compilation cycle!

私野 2024-08-22 20:56:52

Java 没有通用的 define 预处理器指令。

对于常量,建议将它们声明为static Finals,如

private static final int PROTEINS = 100;

这样的声明将由编译器内联(如果该值是编译时常量)。

另请注意,公共静态最终常量字段是公共接口的一部分,它们的值不应更改(因为编译器内联它们)。如果您确实更改了该值,则需要重新编译引用该常量字段的所有源。

Java doesn't have a general purpose define preprocessor directive.

In the case of constants, it is recommended to declare them as static finals, like in

private static final int PROTEINS = 100;

Such declarations would be inlined by the compilers (if the value is a compile-time constant).

Please note also that public static final constant fields are part of the public interface and their values shouldn't change (as the compiler inlines them). If you do change the value, you would need to recompile all the sources that referenced that constant field.

記柔刀 2024-08-22 20:56:52

Java 预处理器,它提供了 #define、#ifdef、#ifndef 等指令许多其他人,例如 PostgresJDBC 团队使用它来为不同情况生成源并且不重复代码。

There is preprocessor for Java which provides directives like #define, #ifdef, #ifndef and many others, for instance PostgresJDBC team uses it to generate sources for different cases and to not duplicate code.

从﹋此江山别 2024-08-22 20:56:52

最易读的解决方案是使用 静态导入。那么您将不需要需要使用AnotherClass.constant

编写一个类,将常量作为 public static 字段。

package ConstantPackage;

public class Constant {
    public static int PROTEINS = 1;
}

然后只需在需要常量的地方使用静态导入即可。

import static ConstantPackage.Constant.PROTEINS;

public class StaticImportDemo {

    public static void main(String[]args) {

        int[] myArray = new int[5];
        myArray[PROTEINS] = 0;

    }
}

要了解有关静态导入的更多信息,请参阅此堆栈溢出问题

Most readable solution is using Static Import. Then you will not need to use AnotherClass.constant.

Write a class with the constant as public static field.

package ConstantPackage;

public class Constant {
    public static int PROTEINS = 1;
}

Then just use Static Import where you need the constant.

import static ConstantPackage.Constant.PROTEINS;

public class StaticImportDemo {

    public static void main(String[]args) {

        int[] myArray = new int[5];
        myArray[PROTEINS] = 0;

    }
}

To know more about Static Import please see this stack overflow question.

驱逐舰岛风号 2024-08-22 20:56:52

Manifold 预处理器 作为 javac 实现编译器插件专为 Java 源代码的条件编译而设计。它使用熟悉的 C/C++ 风格的指令:#define、#undef、#if、#elif、#else、#endif、#error。和#警告。

它有 Maven 和 Gradle 插件。

Manifold Preprocessor implemented as a javac compiler plugin is designed exclusively for conditional compilation of Java source code. It uses familiar C/C++ style of directives: #define, #undef, #if, #elif, #else, #endif, #error. and #warning.

It has Maven and Gradle plugins.

满地尘埃落定 2024-08-22 20:56:52

最简单的答案是“没有直接方法获取它,因为没有预编译器”
但你可以自己做。使用类,然后将变量定义为final,以便在整个程序中将其视为常量
不要忘记将final和variable用作public或protected而不是private,否则您将无法从该类外部访问它

Simplest Answer is "No Direct method of getting it because there is no pre-compiler"
But you can do it by yourself. Use classes and then define variables as final so that it can be assumed as constant throughout the program
Don't forget to use final and variable as public or protected not private otherwise you won't be able to access it from outside that class

困倦 2024-08-22 20:56:52

Java Primitive Specializations Generator 支持 /* 和 */, /* 定义 *//* if */ ... /* elif */ ... /* endif */ 块,允许执行某种操作Java代码中的宏生成,类似于这个答案中提到的java-comment-preprocessor。

JPSG 有 Maven 和 Gradle 插件。

Java Primitive Specializations Generator supports /* with */, /* define */ and /* if */ ... /* elif */ ... /* endif */ blocks which allow to do some kind of macro generation in Java code, similar to java-comment-preprocessor mentioned in this answer.

JPSG has Maven and Gradle plugins.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文