samedi 14 mars 2020

How to edit method annotation attributes on runtime?

I have a simple annotation for editing keys of a map on runtime:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface UpdateKey
{
    String oldKey() default "";    //The key that needs to be replaced

    String newKey() default "";    //The new key

}

And i am using it on a method in some class:

public class CustomMap
{
    @UpdateKey(oldKey = "description", newKey = "productName")
    public void editMap(Map<String,String> map) throws NoSuchMethodException
    {
        //get the annotation values
        UpdateKey updateKey = this.getClass().getMethod("editMap").getAnnotation(UpdateKey.class);

        //save value and delete old key
        Object obj = map.remove(updateKey.oldKey());

        //set the value to the new key
        map.put(updateKey.newKey(),obj);
    }
}

But nothing seems to work to manipulate this annotation before calling the method, i already tried :

        // get the edit map method
        Method method = CustomMap.class.getDeclaredMethod("editMap");

        // get the annotation 
        UpdateKey updateKeyAnnotation = method.getDeclaredAnnotation(UpdateKey.class);

        Object handler = Proxy.getInvocationHandler(updateKeyAnnotation);

        //this is retrieving the reflection class fields NOT my annotation fields
        sout(handler.getClass().getDeclaredFields());

        Field f;

        //of course this will fail since there is no oldKey field in the reflection class
        f = handler.getClass().getDeclaredField("oldKey");  





Aucun commentaire:

Enregistrer un commentaire