Create an annotation instance in Kotlin

I have a structure written in Java, which, using reflection, receives the fields in the annotation and makes some decisions based on them. At some point, I can also create a special instance of the annotation and set the fields myself. This part looks something like this:

public @interface ThirdPartyAnnotation{
    String foo();
}

class MyApp{
    ThirdPartyAnnotation getInstanceOfAnnotation(final String foo)
        {
            ThirdPartyAnnotation annotation = new ThirdPartyAnnotation()
            {
                @Override
                public String foo()
                {
                    return foo;
                }

            }; 
            return annotation;
        }
}

Now I'm trying to do the same in Kotlin. Keep in mind that the annotation is in a third-party bank. Anyway, here is how I tried it in Kotlin:

class MyApp{
               fun getAnnotationInstance(fooString:String):ThirdPartyAnnotation{
                    return ThirdPartyAnnotation(){
                        override fun foo=fooString
                }
    }

But the compiler complains: annotation class cannot be created

So the question is: how do I do this in Kotlin?

+4
source share
1 answer

, , , . , , , :

class MyApp {
    fun getInstanceOfAnnotation(foo: String): ThirdPartyAnnotation {
        val annotationListener = object : InvocationHandler {
            override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?): Any? {
                return when (method?.name) {
                    "foo" -> foo
                    else -> FindBy::class.java
                }
            }
        }
        return Proxy.newProxyInstance(ThirdPartyAnnotation::class.java.classLoader, arrayOf(ThirdPartyAnnotation::class.java), annotationListener) as ThirdPartyAnnotation
    }
}
+2

Source: https://habr.com/ru/post/1615726/


All Articles