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

Support class extraction provided by annotation #1039

Merged
merged 1 commit into from Jul 16, 2022

Conversation

midery
Copy link

@midery midery commented Jul 10, 2022

I've found a bug in method KSAnnotation.getAnnotationsByType when trying to access class field of annotation.

For example, we have custom class and custom annotation that takes this class as a parameter declared in module owner-api:

interface CodeOwner
object KspTeam : CodeOwner

annotation class OwnerAnnotation(val clazz: KClass<out CodeOwner>)

And processor which simply logs code owners is declared in module owners-processor:

class OwnerProcessor(private val logger: KSPLogger) : SymbolProcessor {

    @OptIn(KspExperimental::class)
    override fun process(resolver: Resolver): List<KSAnnotated> {
        resolver.getSymbolsWithAnnotation("com.example.processor.OwnerAnnotation")
            .forEach {
                val annotation = it.getAnnotationsByType(OwnerAnnotation::class).first()
                logger.info(annotation.clazz.toString())
            }
        return emptyList()
    }
}

Annotation usage will be pretty straight-forward and declared in our app module:

@OwnerAnnotation(KspTeam::class)
class PieceOfCode

If we'll try to build module with PieceOfCode and process it via OwnerProcessor - we will get build error:

Caused by: com.google.devtools.ksp.KSTypeNotPresentException: java.lang.ClassNotFoundException: com.example.myapplication.RealCodeOwner
	at com.google.devtools.ksp.UtilsKt.asClass(utils.kt:505)
	at com.google.devtools.ksp.UtilsKt.createInvocationHandler$lambda-8(utils.kt:381)
	at com.sun.proxy.$Proxy25.clazz(Unknown Source)
	at com.example.processor.OwnerProcessor.process(OwnerProcessor.kt:22)

That happens because classloader from module owners-processor can't access classes from owners-api and simply ignores them.

We can fix this behavior if we'll supply Class.forName method with classLoader from annotation, which is located in the same module as the parameter.

@neetopia neetopia merged commit 25ed6bb into google:main Jul 16, 2022
3 checks passed
@neetopia
Copy link
Collaborator

Thanks for the fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants