在运行时添加Java注释

Cla*_*ton 68 java annotations runtime

是否可以在运行时向对象添加注释(在我的情况下特别是一个方法)?

更多解释:我有两个模块,moduleA和moduleB.moduleB依赖于moduleA,它不依赖于任何东西.(modA是我的核心数据类型和接口等,modB是db/data层)modB也取决于externalLibrary.在我的例子中,modB将一个类从modA移交给externalLibrary,这需要某些方法进行注释.具体的注释都是externalLib的一部分,正如我所说,modA不依赖于externalLib,我想保持这种方式.

那么,这是可能的,还是你有其他方法来看待这个问题的建议?

Chs*_*y76 39

它可以通过字节码检测库,如Javassist.

特别是,请参阅AnnotationsAttribute类以获取有关如何创建/设置注释的示例以及有关字节码API的教程部分,以获取有关如何操作类文件的一般指导.

这不过是简单明了的事情 - 我不推荐这种方法,建议你考虑汤姆的答案,除非你需要为大量的类做这个(或者直到运行时你才能使用这些类)适配器是不可能的).


Bal*_*der 23

也可以使用Java反射API在运行时向Java类添加Annotation.基本上必须重新创建类中定义的内部Annotation映射java.lang.Class(或者内部类中定义的Java 8 java.lang.Class.AnnotationData).当然,这种方法非常糟糕,并且可能随时针对较新的Java版本而中断.但是对于快速和脏的测试/原型设计,这种方法有时很有用.

Java 8的概念示例:

public final class RuntimeAnnotations {

    private static final Constructor<?> AnnotationInvocationHandler_constructor;
    private static final Constructor<?> AnnotationData_constructor;
    private static final Method Class_annotationData;
    private static final Field Class_classRedefinedCount;
    private static final Field AnnotationData_annotations;
    private static final Field AnnotationData_declaredAnotations;
    private static final Method Atomic_casAnnotationData;
    private static final Class<?> Atomic_class;

    static{
        // static initialization of necessary reflection Objects
        try {
            Class<?> AnnotationInvocationHandler_class = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
            AnnotationInvocationHandler_constructor = AnnotationInvocationHandler_class.getDeclaredConstructor(new Class[]{Class.class, Map.class});
            AnnotationInvocationHandler_constructor.setAccessible(true);

            Atomic_class = Class.forName("java.lang.Class$Atomic");
            Class<?> AnnotationData_class = Class.forName("java.lang.Class$AnnotationData");

            AnnotationData_constructor = AnnotationData_class.getDeclaredConstructor(new Class[]{Map.class, Map.class, int.class});
            AnnotationData_constructor.setAccessible(true);
            Class_annotationData = Class.class.getDeclaredMethod("annotationData");
            Class_annotationData.setAccessible(true);

            Class_classRedefinedCount= Class.class.getDeclaredField("classRedefinedCount");
            Class_classRedefinedCount.setAccessible(true);

            AnnotationData_annotations = AnnotationData_class.getDeclaredField("annotations");
            AnnotationData_annotations.setAccessible(true);
            AnnotationData_declaredAnotations = AnnotationData_class.getDeclaredField("declaredAnnotations");
            AnnotationData_declaredAnotations.setAccessible(true);

            Atomic_casAnnotationData = Atomic_class.getDeclaredMethod("casAnnotationData", Class.class, AnnotationData_class, AnnotationData_class);
            Atomic_casAnnotationData.setAccessible(true);

        } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | NoSuchFieldException e) {
            throw new IllegalStateException(e);
        }
    }

    public static <T extends Annotation> void putAnnotation(Class<?> c, Class<T> annotationClass, Map<String, Object> valuesMap){
        putAnnotation(c, annotationClass, annotationForMap(annotationClass, valuesMap));
    }

    public static <T extends Annotation> void putAnnotation(Class<?> c, Class<T> annotationClass, T annotation){
        try {
            while (true) { // retry loop
                int classRedefinedCount = Class_classRedefinedCount.getInt(c);
                Object /*AnnotationData*/ annotationData = Class_annotationData.invoke(c);
                // null or stale annotationData -> optimistically create new instance
                Object newAnnotationData = createAnnotationData(c, annotationData, annotationClass, annotation, classRedefinedCount);
                // try to install it
                if ((boolean) Atomic_casAnnotationData.invoke(Atomic_class, c, annotationData, newAnnotationData)) {
                    // successfully installed new AnnotationData
                    break;
                }
            }
        } catch(IllegalArgumentException | IllegalAccessException | InvocationTargetException | InstantiationException e){
            throw new IllegalStateException(e);
        }

    }

    @SuppressWarnings("unchecked")
    private static <T extends Annotation> Object /*AnnotationData*/ createAnnotationData(Class<?> c, Object /*AnnotationData*/ annotationData, Class<T> annotationClass, T annotation, int classRedefinedCount) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Map<Class<? extends Annotation>, Annotation> annotations = (Map<Class<? extends Annotation>, Annotation>) AnnotationData_annotations.get(annotationData);
        Map<Class<? extends Annotation>, Annotation> declaredAnnotations= (Map<Class<? extends Annotation>, Annotation>) AnnotationData_declaredAnotations.get(annotationData);

        Map<Class<? extends Annotation>, Annotation> newDeclaredAnnotations = new LinkedHashMap<>(annotations);
        newDeclaredAnnotations.put(annotationClass, annotation);
        Map<Class<? extends Annotation>, Annotation> newAnnotations ;
        if (declaredAnnotations == annotations) {
            newAnnotations = newDeclaredAnnotations;
        } else{
            newAnnotations = new LinkedHashMap<>(annotations);
            newAnnotations.put(annotationClass, annotation);
        }
        return AnnotationData_constructor.newInstance(newAnnotations, newDeclaredAnnotations, classRedefinedCount);
    }

    @SuppressWarnings("unchecked")
    public static <T extends Annotation> T annotationForMap(final Class<T> annotationClass, final Map<String, Object> valuesMap){
        return (T)AccessController.doPrivileged(new PrivilegedAction<Annotation>(){
            public Annotation run(){
                InvocationHandler handler;
                try {
                    handler = (InvocationHandler) AnnotationInvocationHandler_constructor.newInstance(annotationClass,new HashMap<>(valuesMap));
                } catch (InstantiationException | IllegalAccessException
                        | IllegalArgumentException | InvocationTargetException e) {
                    throw new IllegalStateException(e);
                }
                return (Annotation)Proxy.newProxyInstance(annotationClass.getClassLoader(), new Class[] { annotationClass }, handler);
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TestAnnotation {
    String value();
}

public static class TestClass{}

public static void main(String[] args) {
    TestAnnotation annotation = TestClass.class.getAnnotation(TestAnnotation.class);
    System.out.println("TestClass annotation before:" + annotation);

    Map<String, Object> valuesMap = new HashMap<>();
    valuesMap.put("value", "some String");
    RuntimeAnnotations.putAnnotation(TestClass.class, TestAnnotation.class, valuesMap);

    annotation = TestClass.class.getAnnotation(TestAnnotation.class);
    System.out.println("TestClass annotation after:" + annotation);
}
Run Code Online (Sandbox Code Playgroud)

输出:

TestClass annotation before:null
TestClass annotation after:@RuntimeAnnotations$TestAnnotation(value=some String)
Run Code Online (Sandbox Code Playgroud)

这种方法的局限性:

  • 新版本的Java可能随时破坏代码.
  • 上面的示例仅适用于Java 8 - 使其适用于较旧的Java版本需要在运行时检查Java版本并相应地更改实现.
  • 如果带注释的类被重新定义(例如在调试期间),则注释将丢失.
  • 未经彻底测试; 不确定是否有任何不良副作用 - 使用风险自负 ......

  • @heez我已经在字段和方法上完成了这项工作.您可以看到[AnnotationUtil.java](https://github.com/XDean/Java-EX/blob/master/src/main/java/xdean/jex/util/reflect/AnnotationUtil.java). (2认同)
  • @DeanXu感谢您的帮助,看起来它已移至https://github.com/XDean/Java-EX/blob/master/src/main/java/cn/xdean/jex/reflect/AnnotationUtil.java (2认同)

Tom*_*Tom 21

在运行时不可能添加注释,听起来你需要引入一个模块B用来从模块A包装对象的适配器,暴露所需的带注释的方法.

  • 我决定采取混合方法来解决这个问题。现在,我刚刚注释了原始方法(添加对 modA 的依赖项),认为我可以稍后提取注释并使用适配器。谢谢各位! (2认同)

Ren*_*ato 8

可以通过Proxy在运行时创建注释。然后,您可以按照其他答案中的建议,通过反射将它们添加到您的 Java 对象中(但您可能最好找到一种替代方法来处理该问题,因为通过反射弄乱现有类型可能很危险且难以调试)。

但这并不是很容易......我写了一个名为Javaanna的库,我希望可以使用一个干净的 API 轻松地做到这一点。

它在JCenterMaven Central 中

使用它:

@Retention( RetentionPolicy.RUNTIME )
@interface Simple {
    String value();
}

Simple simple = Javanna.createAnnotation( Simple.class, 
    new HashMap<String, Object>() {{
        put( "value", "the-simple-one" );
    }} );
Run Code Online (Sandbox Code Playgroud)

如果地图的任何条目与注释声明的字段和类型不匹配,则会抛出异常。如果缺少任何没有默认值的值,则会抛出异常。

这使得可以假设成功创建的每个注解实例都与编译时注解实例一样安全。

作为奖励,这个库还可以解析注释类并将注释的值作为 Map 返回:

Map<String, Object> values = Javanna.getAnnotationValues( annotation );
Run Code Online (Sandbox Code Playgroud)

这对于创建迷你框架很方便。