Rooted In Develop

Kotlin - annotation, reflection 본문

Back End/Kotlin

Kotlin - annotation, reflection

RootedIn 2023. 6. 17. 18:15

애노테이션 사용 지점 대상 지정

대상 설명
property 프로퍼티 전체
field 프로퍼티에 생성되는 필드
get 프로퍼티 게터
set 프로퍼티 세터
receiver 확장 함수, 프로퍼티의 수신 객체 파라미터
param 생성자 파라미터
setparam 세터 파라미터
delegate 위임 프로퍼티의 위임 인스턴스를 담아둔 필드
file 파일 안에 선언된 최상위 함수와 프로퍼티를 담아두는 클래스
class HasTempFolder {
  @get:Rule
  val folder = TemporaryFolder()
  
  @Test
  fun testUsingTempFolder() {
    val createdFile = folder.newFile("myFile.txt")
    val createdFolder = folder.newFolder("subfolder")
  }
}

애노테이션 정의

annotation class JsonName(val name: String)

메타애노테이션 : 애노테이션 클래스에 적용할 수 있는 애노테이션

@Target(AnnotationTarget.PROPERTY)
annotation classJsonExclude

@Target(AnnotationTarget.ANNOTATION_CLASS)
annotation class BindingAnnotation

@BindingAnnotation
annotation class MyBinding

- AnnotationTarget.PROPERTY : 자바에서 사용 불가
- AnnotationTarget.FIELD : 자바에서 사용 가능

annotation class DeserializeInterface(val targetClass: KClass<out Any>)

interface ValueSerializer<T> {
  fun toJsonValue(value: T) : Any?
  fun fromJsonValue(jsonVluae: Any?) : T
}

annotation class CustomSerializer(val serializerClass: KClass<out ValueSerializer<*>>)

data class Person(
  val name: String,
  @CustomSerializer(DateSerializer::class) val birthDate: Date
)

리플렉션 : KClass, KCallable, KFunction, KProperty

- KFunction, KProperty 는 모두 KCallable 확장
- KCallable은 제네릭 call 메서드 제공
- KCallable.callBy 메서드 호출하면 디폴트 파라미터 값 사용 가능
- KFunction는 invoke 메서드로 함수 호출 가능
- Kproperty0은 최상위 프로퍼티나 변수, KProperty1은 수신 객체가 있는 프로퍼티에 접근
- KMutableProperty0은 KProperty0을 확장, set 메서드로 값 변경 가능

'Back End > Kotlin' 카테고리의 다른 글

Kotlin - DSL  (0) 2023.06.24
Kotlin - 제네릭스  (0) 2023.06.10
Kotlin - 고차 함수  (0) 2023.06.03
Kotlin - 연산자 오버로딩  (0) 2023.05.27
Kotlin - 타입 시스템  (0) 2023.05.06
Comments