Spec-Zone.ru › Kotlin 2

Справочник по переходу с обработки аннотаций Java на KSP

Элементы программы

Java

Ближайший аналог в KSP

Примечания

AnnotationMirror

KSAnnotation

AnnotationValue

KSValueArguments

Element

KSDeclaration/KSDeclarationContainer

ExecutableElement

KSFunctionDeclaration

PackageElement

KSFile

KSP не представляет пакеты в виде элементов программы

Parameterizable

KSDeclaration

QualifiedNameable

KSDeclaration

TypeElement

KSClassDeclaration

TypeParameterElement

KSTypeParameter

VariableElement

KSValueParameter/KSPropertyDeclaration

Типы

KSP требует явного разрешения типов, поэтому некоторые функции Java можно реализовать только с помощью KSType и соответствующих элементов до разрешения типов.

Java

Ближайший аналог в KSP

Примечания

ArrayType

KSBuiltIns.arrayType

DeclaredType

KSType/KSClassifierReference

ErrorType

KSType.isError

ExecutableType

KSType/KSCallableReference

IntersectionType

KSType/KSTypeParameter

NoType

KSType.isError

В KSP отсутствует

NullType

В KSP отсутствует

PrimitiveType

KSBuiltIns

Не совсем совпадает с примитивным типом в Java

ReferenceType

KSTypeReference

TypeMirror

KSType

TypeVariable

KSTypeParameter

UnionType

Не применимо

В Kotlin в каждом блоке catch может быть только один тип. UnionType также недоступен даже процессорам аннотаций Java

WildcardType

KSType/KSTypeArgument

Разное

Java

Ближайший аналог в KSP

Примечания

Name

KSName

ElementKind

ClassKind/FunctionKind

Modifier

Modifier

NestingKind

ClassKind/FunctionKind

AnnotationValueVisitor

ElementVisitor

KSVisitor

AnnotatedConstruct

KSAnnotated

TypeVisitor

TypeKind

KSBuiltIns

Некоторые можно найти во встроенных элементах; в противном случае см. KSClassDeclaration для DeclaredType

ElementFilter

Collection.filterIsInstance

ElementKindVisitor

KSVisitor

ElementScanner

KSTopDownVisitor

SimpleAnnotationValueVisitor

В KSP не требуется

SimpleElementVisitor

KSVisitor

SimpleTypeVisitor

TypeKindVisitor

Types

Resolver/utils

Некоторые из utils также интегрированы в интерфейсы символов

Elements

Resolver/utils

Подробности

Узнайте, как реализовать с помощью KSP функциональность API обработки аннотаций Java.

AnnotationMirror

Java

Аналог в KSP

getAnnotationType

ksAnnotation.annotationType

getElementValues

ksAnnotation.arguments

AnnotationValue

Java

Аналог в KSP

getValue

ksValueArgument.value

Element

Java

Аналог в KSP

asType

ksClassDeclaration.asType(...) доступен только для KSClassDeclaration. Необходимо указать аргументы типа.

getAnnotation

Предстоит реализовать

getAnnotationMirrors

ksDeclaration.annotations

getEnclosedElements

ksDeclarationContainer.declarations

getEnclosingElements

ksDeclaration.parentDeclaration

getKind

Проверьте тип и выполните приведение согласно ClassKind или FunctionKind

getModifiers

ksDeclaration.modifiers

getSimpleName

ksDeclaration.simpleName

ExecutableElement

Java

Аналог в KSP

getDefaultValue

Предстоит реализовать

getParameters

ksFunctionDeclaration.parameters

getReceiverType

ksFunctionDeclaration.parentDeclaration

getReturnType

ksFunctionDeclaration.returnType

getSimpleName

ksFunctionDeclaration.simpleName

getThrownTypes

В Kotlin не требуется

getTypeParameters

ksFunctionDeclaration.typeParameters

isDefault

Проверьте, является ли родительское объявление интерфейсом

isVarArgs

ksFunctionDeclaration.parameters.any { it.isVarArg }

Parameterizable

Java

Аналог в KSP

getTypeParameters

ksFunctionDeclaration.typeParameters

QualifiedNameable

Java

Аналог в KSP

getQualifiedName

ksDeclaration.qualifiedName

TypeElement

Java

Аналог в KSP

getEnclosedElements

ksClassDeclaration.declarations

getEnclosingElement

ksClassDeclaration.parentDeclaration

getInterfaces

// Should be able to do without resolution
ksClassDeclaration.superTypes
    .map { it.resolve() }
    .filter { (it?.declaration as? KSClassDeclaration)?.classKind == ClassKind.INTERFACE }

getNestingKind

Проверьте модификатор KSClassDeclaration.parentDeclaration и inner

getQualifiedName

ksClassDeclaration.qualifiedName

getSimpleName

ksClassDeclaration.simpleName

getSuperclass

// Should be able to do without resolution
ksClassDeclaration.superTypes
    .map { it.resolve() }
    .filter { (it?.declaration as? KSClassDeclaration)?.classKind == ClassKind.CLASS }

getTypeParameters

ksClassDeclaration.typeParameters

TypeParameterElement

Java

Аналог в KSP

getBounds

ksTypeParameter.bounds

getEnclosingElement

ksTypeParameter.parentDeclaration

getGenericElement

ksTypeParameter.parentDeclaration

VariableElement

Java

Аналог в KSP

getConstantValue

Предстоит реализовать

getEnclosingElement

ksValueParameter.parentDeclaration

getSimpleName

ksValueParameter.simpleName

ArrayType

Java

Аналог в KSP

getComponentType

ksType.arguments.first()

DeclaredType

Java

Аналог в KSP

asElement

ksType.declaration

getEnclosingType

ksType.declaration.parentDeclaration

getTypeArguments

ksType.arguments

ExecutableType

KSType функции — это просто сигнатура, представленная семейством FunctionN<R, T1, T2, ..., TN>.

Java

Аналог в KSP

getParameterTypes

ksType.declaration.typeParameters, ksFunctionDeclaration.parameters.map { it.type }

getReceiverType

ksFunctionDeclaration.parentDeclaration.asType(...)

getReturnType

ksType.declaration.typeParameters.last()

getThrownTypes

В Kotlin не требуется

getTypeVariables

ksFunctionDeclaration.typeParameters

IntersectionType

Java

Аналог в KSP

getBounds

ksTypeParameter.bounds

TypeMirror

Java

Аналог в KSP

getKind

Для примитивных типов сопоставьте с типами в KSBuiltIns, для типа Unit — с соответствующим типом; в остальных случаях — с объявленными типами

TypeVariable

Java

Аналог в KSP

asElement

ksType.declaration

getLowerBound

Требуется решить. Нужно только в том случае, если предоставлена фиксация переменных и требуется явная проверка границ.

getUpperBound

ksTypeParameter.bounds

WildcardType

Java

Аналог в KSP

getExtendsBound

if (ksTypeArgument.variance == Variance.COVARIANT) ksTypeArgument.type else null

getSuperBound

if (ksTypeArgument.variance == Variance.CONTRAVARIANT) ksTypeArgument.type else null

Элементы

Java

Аналог в KSP

getAllAnnotationMirrors

KSDeclarations.annotations

getAllMembers

getAllFunctions, getAllProperties предстоит реализовать

getBinaryName

Требуется решить; см. спецификацию Java

getConstantExpression

Здесь есть константное значение, а не выражение

getDocComment

Предстоит реализовать

getElementValuesWithDefaults

Предстоит реализовать

getName

resolver.getKSNameFromString

getPackageElement

Пакеты не поддерживаются, но информацию о них можно получить. Выполнять операции с пакетами в KSP нельзя

getPackageOf

Пакеты не поддерживаются

getTypeElement

Resolver.getClassDeclarationByName

hides

Предстоит реализовать

isDeprecated

KsDeclaration.annotations.any { 
    it.annotationType.resolve()!!.declaration.qualifiedName!!.asString() == Deprecated::class.qualifiedName
}

overrides

KSFunctionDeclaration.overrides/KSPropertyDeclaration.overrides (функция-член соответствующего класса)

printElements

В большинстве классов KSP реализована базовая поддержка toString()

Типы

Java

Аналог в KSP

asElement

ksType.declaration

asMemberOf

resolver.asMemberOf

boxedClass

Не требуется

capture

Требуется решить

contains

KSType.isAssignableFrom

directSuperTypes

(ksType.declaration as KSClassDeclaration).superTypes

erasure

ksType.starProjection()

getArrayType

ksBuiltIns.arrayType.replace(...)

getDeclaredType

ksClassDeclaration.asType

getNoType

ksBuiltIns.nothingType/null

getNullType

В зависимости от контекста может пригодиться KSType.markNullable

getPrimitiveType

Не требуется; проверьте KSBuiltins

getWildcardType

Используйте Variance там, где ожидается KSTypeArgument

isAssignable

ksType.isAssignableFrom

isSameType

ksType.equals

isSubsignature

functionTypeA == functionTypeB/functionTypeA == functionTypeB.starProjection()

isSubtype

ksType.isAssignableFrom

unboxedType

Не требуется

12 августа 2026 г.
Как KSP моделирует код KotlinИнкрементальная обработка

© 2010–2026 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/docs/ksp-reference.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API