Program Club

자바에서 #define

proclub 2020. 11. 10. 22:32
반응형

자바에서 #define


Java로 프로그래밍을 시작하고 있으며 C ++에 해당하는 것이 있는지 궁금 #define합니다.

Google의 빠른 검색은 그렇지 않다고 말하지만 Java에 비슷한 것이 있는지 누구든지 말해 줄 수 있습니까? 내 코드를 더 읽기 쉽게 만들려고합니다.

대신에 예를 들어 myArray[0]쓸 수 있기를 원합니다 myArray[PROTEINS].


아니요, 프리 컴파일러가 없기 때문입니다. 그러나 귀하의 경우 다음과 같은 것을 얻을 수 있습니다.

class MyClass
{
    private static final int PROTEINS = 0;

    ...

    MyArray[] foo = new MyArray[PROTEINS];

}

컴파일러는 PROTEINS결코 변경할 수 없다는 것을 알아 차리고 인라인 할 것입니다.

그것이 될 수 있도록 참고 상수에 대한 액세스 수정, 여기에 중요하지 않은 것을 public또는 protected여러 클래스에서 동일한 상수를 다시 사용하기를 원한다면, 개인 대신.


주석 공간이 너무 작으므로 .NET Framework 사용에 대한 추가 정보가 있습니다 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각각에 대해 다른 값을 갖도록 변경 하고 class를 컴파일하십시오 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은 참조로 유지됩니다.

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.


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!


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.


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.


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


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.


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.

참고URL : https://stackoverflow.com/questions/1927107/define-in-java

반응형