파이썬에서 자바 패키지 및 사용자 자바 기능 호출
글. 수알치 오상문
파이썬에서 호출한 자바 예제입니다.
컴파일해서 JpypeTest.jar 파일로 생성합니다.
[JpypeTest.java]
// package com.jpype.utils;
public class JpypeTest {
public static String reverse(String str) {
StringBuilder buf = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
buf.append(str.charAt(i));
}
return buf.toString();
}
}
아래는 자바 패키지 및 사용자 jar 파일을 호출하는 파이썬 예제입니다.
[main.py]
from py4j.java_gateway import *
# JavaGateway를 시작할 때 JpypeTest.jar 파일을 클래스 패스에 추가합니다.
jar_path = "JpypeTest.jar"
try:
port = launch_gateway()
gateway = JavaGateway(gateway_parameters=GatewayParameters(port=port),
callback_server_parameters=CallbackServerParameters(port=0))
random = gateway.jv m.java.util.Random()
print(random)
# java.lang.System 클래스의 getProperty 메서드 호출 예제
system = gateway.jvm.java.lang.System
print(system.getProperty("java.version"))
# JAR 파일에서 클래스를 임포트하고 사용합니다.
my_package = gateway.jvm # JAR 파일 내의 패키지명 없는 경우 이렇게 지정
# my_package = gateway.jvm.패키지명 # 패키지명이 있는 경우에 이렇게 지정
jpype_test_class = my_package.JpypeTest # 클래스명 지정
# JpypeTest 클래스의 메서드를 호출하고 결과를 출력합니다.
result = jpype_test_class.reverse("안녕하세요") # JpypeTest 클래스의 reverse 메서드 호출
print("결과: ", result)
except Exception as e:
print("ERROR:", e)
finally:
gateway.shutdown()
[실행 결과] python main.py
java.util.Random@29dbb124
1.8.0_381
결과: 요세하녕안
'Python 활용' 카테고리의 다른 글
2023, 파이썬 유용한 라이브러리 (0) | 2023.10.25 |
---|---|
Python + Cython 두 번째 글 (1) | 2023.10.13 |
pip install jpype 설치 에러 (0) | 2023.10.05 |
Python, matplotlib 한글 깨짐 (Windows) (0) | 2023.09.26 |
Python + Cython 첫 번째 (0) | 2023.09.06 |