Is there any way to create an annotation instance?...
# serialization
j
Is there any way to create an annotation instance? I've got a weird situation where it would be nice to have.
n
i think you can get a instance of a annotation and pass it around.. but instantiating it will not work, might explaining where it is useful and why ? maybe there is a better alternatives
j
I’m creating an alternate plugin for KotlinX serialization that handles polymorphism for all platforms and gives access to a bunch of extra reflective information. I have everything in place except that I can’t generate the list of annotations for runtime access. If I can’t make an annotation instance, I can always provide a different way to read annotation data, but then the serializers that depend on annotations would either have to try both ways of reading the data or would just simply ignore annotations when using my plugin.
I’m guessing then that the built-in KotlinX plugin cheats in instantiating them somehow?
n
you mean
descriptor.getElementAnnotations(index)
?
j
Yup. Unfortunately I can’t implement the interface correctly unless I can instantiate the annotations - my plugin just generates normal source code for the serializers.
n
well i am pretty sure thats where the compiler plugin comes into play
you might be able to get the annotations via annotationProcessor, storing them in some format and then generating source based on that
but you would have to wrap the values of the annotations in some fake annotation objects i think
j
I already am reading the source, and successfully have the annotation information. And that’s what I did previously -
data class AnnotationInfo(val name: String, val values: Map<String, Any?>)
- but that doesn’t match the interface.
I just need some way to actually create an annotation object if I want to match the interface exactly.
n
that will make the runtime depend on reflection though
you could generate the annotation wrapper with a method to get the real one
j
Yeah, depending on reflection isn’t an option unfortunately because the whole point of this plugin is that polymorphic serialization works on all platforms, and both JS and Native don’t support enough of reflection to get it working.
n
in that case i think you need to make a compiler plugin fur just that bit
j
Yeah, unfortunately I think that’s what has to happen
I figured out how the plugin does it partly - it literally rewrites the class during compilation to have an “Impl” that it uses to create them. Even better, it’s not possible to even write the annotations manually to work like that - it’s an extension of a final class, which is rejected by the compiler but for some reason allowed in the case of the plugin.