使用反射在运行时覆盖方法级别@annotation,适用于类级别

时间:2017-10-25 16:38:28

标签: java reflection interface override

问题:我可以使用以下方法成功覆盖类级别注释:

public static void alterClassAnnotation(Class classToLookFor, Class<? extends Annotation> annotationToAlter,Annotation annotationValue) {
        if (isJDK7OrLower()) {
            try {
                Field annotations = Class.class.getDeclaredField(ANNOTATIONS);
                annotations.setAccessible(true);
                Map<Class<? extends Annotation>, Annotation> map =
                    (Map<Class<? extends Annotation>, Annotation>) annotations.get(classToLookFor);
                map.put(annotationToAlter, annotationValue);
            } catch (Exception  e) {
                e.printStackTrace();
            }
        } else {
            try {
                //In JDK8 Class has a private method called annotationData().
                //We first need to invoke it to obtain a reference to AnnotationData class which is a private class
                Method method = Class.class.getDeclaredMethod(ANNOTATION_DATA, null);
                method.setAccessible(true);
                //Since AnnotationData is a private class we cannot create a direct reference to it. We will have to
                //manage with just Object
                Object annotationData = method.invoke(classToLookFor);
                //We now look for the map called "annotations" within AnnotationData object.
                Field annotations = annotationData.getClass().getDeclaredField(ANNOTATIONS);
                annotations.setAccessible(true);
                Map<Class<? extends Annotation>, Annotation> map =
                    (Map<Class<? extends Annotation>, Annotation>) annotations.get(annotationData);
                map.put(annotationToAlter, annotationValue);
            } catch (Exception  e) {
                e.printStackTrace();
            }
        }
    }

我对反射API感到困惑,如何修改此代码以覆盖方法级别参数的值?我有3个注释,其中2个可以在类级别设置,所以我用这个代码成功地覆盖了它们,但是如果注释是否反对方法本身呢?

我的接口实现类:

import java.lang.annotation.Annotation;

import io.qameta.allure.junit4.DisplayName;
public class DynamicDisplayName implements DisplayName {

    private String value;

    public DynamicDisplayName(String value) {
        this.value = value;
    }

    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }

    @Override
    public String value() {
        return value;
    }

}

我已成功覆盖了Issue和TmsLink,这是我的代码(这两个接口在类级别都能正常运行)

Issue issue = SaveCourse.class.getAnnotation(Issue.class);
DynamicIssue altered = new DynamicIssue(issueId);
AnnotationHelper.alterClassAnnotation(SaveCourse.class, Issue.class, altered);
issue = SaveCourse.class.getAnnotation(Issue.class);                 


DisplayName dname = SaveCourse.class.getAnnotation(DisplayName.class);
DynamicDisplayName dna = new DynamicDisplayName(displayName);
AnnotationHelper.alterClassAnnotation(SaveCourse.class, DisplayName.class, dna);
dname = SaveCourse.class.getAnnotation(DisplayName.class);

TmsLink tmslink = SaveCourse.class.getAnnotation(TmsLink.class);
DynamicTmsLink tmsaltered = new DynamicTmsLink(testCaseId);
AnnotationHelper.alterClassAnnotation(SaveCourse.class, TmsLink.class, tmsaltered);
tmslink = SaveCourse.class.getAnnotation(TmsLink.class);

displayName界面:

/**
 * Used to change display name for test in the report.
 */
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface DisplayName {

    String value();

}

2 个答案:

答案 0 :(得分:1)

这是我的code on github.。你可以使用

addAnnotation(...)
removeAnnotation(...)
changeAnnotationValue(...)

修改ClassFieldMethod上的注释。并使用createAnnotationFromMap创建任何类型的注释。

答案 1 :(得分:1)

对于具有JUnit4的吸引力,我正在使用以下方法在方法级别动态设置DisplayName。

AllureLifecycle oLifecycle = Allure.getLifecycle();
oLifecycle.updateTestCase(testResult -> testResult.setName("My DisplayName");