Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kotlin 의 @JvmName 어노테이션 #153

Open
occidere opened this issue Dec 6, 2020 · 0 comments
Open

Kotlin 의 @JvmName 어노테이션 #153

occidere opened this issue Dec 6, 2020 · 0 comments
Assignees

Comments

@occidere
Copy link
Owner

occidere commented Dec 6, 2020

@JvmName

Kotlin 메서드 또는 클래스를 JVM bytecode 로 변환할 때 사용할 JVM Signature 를 변경한다. 쉽게 말하면 Java 에서 호출할 Kotlin 메서드 또는 클래스의 이름을 지정한 이름으로 바꾸는 것이다.


Example

예를들어 아래와 같은 메서드는 컴파일 에러가 발생한다.

fun printAll(list: List<Int>) {
    println(list)
}

fun printAll(list: List<String>) {
    println(list)
}

에러 내용을 살펴보면 JVM Signature 가 같다고 나오는데, 이는 바이트코드 생성 시 List 의 Generic 값은 구분되지 않기 때문에 두개가 같은 메서드로 판단해버리기 때문이다.
image


이 때 @JvmName 어노테이션을 붙여 직접 생성될 이름을 지정해주면 문제를 해결할 수 있다.
또한 @file:JvmName() 처럼 파일 자체의 이름을 다르게 바꿔서 사용되도록 할 수도 있다.

// 생성한 파일명: PrintUtils.kt
@file:JvmName("Utils") // PrintUtils.kt -> Utils 로 이름 변경해서 호출하도록 명시

@JvmName(name = "printAllInts")
fun printAll(list: List<Int>) {
    println(list)
}

@JvmName(name = "printAllStrings")
fun printAll(list: List<String>) {
    println(list)
}

이제 Java 에서 해당 메서드를 호출해보면 메서드명이 지정한 이름으로 바뀌어 있는 것을 확인할 수 있다.

public static void main(String[] args) {
        // PrintUtilsKt 대신 Utils 로 접근 
	Utils.printAllInts(Arrays.asList(1, 2, 3)); // printAllints()
	Utils.printAllStrings(Arrays.asList("a", "b", "c")); // printAllStrings()
}

반면 Kotlin 에선 내부적으로 올바른 메서드를 선택해서 호출하기 때문에 기존 메서드 이름을 사용해야 한다.

fun main() {
    printAll(listOf(1, 2, 3))
    printAll(listOf("a", "b", "c"))
}

참고

@occidere occidere self-assigned this Dec 6, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant