program tip

Java의 기본 메소드는 무엇이며 어디에 사용해야합니까?

radiobox 2020. 10. 31. 09:33
반응형

Java의 기본 메소드는 무엇이며 어디에 사용해야합니까?


이 질문에 이미 답변이 있습니다.

네이티브 메서드는 추상 메서드와 구문이 동일하지만 어디에서 구현됩니까?


Java의 기본 메소드는 무엇이며 어디에 사용해야합니까?

작은 예를 보면 분명해집니다.

Main.java :

public class Main {
    public native int intMethod(int i);
    public static void main(String[] args) {
        System.loadLibrary("Main");
        System.out.println(new Main().intMethod(2));
    }
}

Main.c :

#include <jni.h>
#include "Main.h"

JNIEXPORT jint JNICALL Java_Main_intMethod(
    JNIEnv *env, jobject obj, jint i) {
  return i * i;
}

컴파일 및 실행 :

javac Main.java
javah -jni Main
gcc -shared -fpic -o libMain.so -I${JAVA_HOME}/include \
  -I${JAVA_HOME}/include/linux Main.c
java -Djava.library.path=. Main

출력 :

4

Oracle JDK 1.8.0_45를 사용하여 Ubuntu 14.04에서 테스트되었습니다.

따라서 다음을 수행 할 수 있습니다.

  • 자바에서 임의의 어셈블리 코드를 사용하여 컴파일 된 동적로드 라이브러리 (여기서는 C로 작성 됨) 호출
  • 결과를 Java로 다시 가져옵니다.

다음과 같은 용도로 사용할 수 있습니다.

  • 더 나은 CPU 어셈블리 명령으로 중요한 섹션에서 더 빠른 코드 작성 (CPU 휴대용 아님)
  • 직접 시스템 호출 (OS 휴대용 아님)

낮은 이식성의 절충과 함께.

C에서 Java를 호출하는 것도 가능하지만 먼저 C로 JVM을 만들어야합니다. C ++에서 Java 함수를 호출하는 방법은 무엇입니까?

함께 플레이 할 수있는 GitHub의 예제 입니다.


이 메서드는 "네이티브"코드로 구현됩니다. 즉, JVM에서 실행되지 않는 코드입니다. 일반적으로 C 또는 C ++로 작성됩니다.

기본 메서드는 일반적으로 다른 프로그래밍 언어로 작성된 시스템 호출 또는 라이브러리와 인터페이스하는 데 사용됩니다.


네이티브 메서드를 어디에 사용하는지 알고 싶습니다.

이상적으로는 전혀 아닙니다. 실제로 일부 기능은 Java에서 사용할 수 없으며 일부 C 코드를 호출해야합니다.

메서드는 C 코드로 구현됩니다.


자바 네이티브 코드 필수 :

  • h / w 액세스 및 제어.
  • 상용 소프트웨어 및 시스템 서비스 사용 [h / w 관련].
  • Java로 포팅되지 않았거나 포팅 될 수없는 레거시 소프트웨어 사용.
  • Using native code to perform time-critical tasks.

hope these points answers your question :)


Native methods allow you to use code from other languages such as C or C++ in your java code. You use them when java doesn't provide the functionality that you need. For example, if I were writing a program to calculate some equation and create a line graph of it, I would use java, because it is the language I am best in. However, I am also proficient in C. Say in part of my program I need to calculate a really complex equation. I would use a native method for this, because I know some C++ and I know that C++ is much faster than java, so if I wrote my method in C++ it would be quicker. Also, say I want to interact with another program or device. This would also use a native method, because C++ has something called pointers, which would let me do that.

참고URL : https://stackoverflow.com/questions/18900736/what-are-native-methods-in-java-and-where-should-they-be-used

반응형