URLClassLoader loads Annotation as com.sun.$Proxy$27

前端 未结 3 1869
小鲜肉
小鲜肉 2021-01-06 08:27

I\'m trying to dynamically load a java class. The basic idea is, that a jar contains modules which get loaded dynamically at runtime. This is how I do it (I know it\'s hacky

3条回答
  •  别那么骄傲
    2021-01-06 09:08

    The fact that the reflection returns a proxy object does not prevent you from gathering information about the annotation and its values.

    The getclass method returns a proxy object:

     log.info("annotation class:" + annotation.getClass());
    

    Output:

     [INFO] annotation class:class com.sun.proxy.$Proxy16class 
    

    The output is that same as in your example, but that is no problem. Having the method (or field) is enough. The additional part is to just invoke the annotation method.

    public void analyseClass(Class myClass) {
    
        for (Method method: myClass.getMethods()) {
            System.out.println("aanotations :" + Arrays.toString(field.getAnnotations()));
    
            for (Annotation annotation : method.getAnnotations()) {
    
                log.info("annotation class:" + annotation.getClass());
                log.info("annotation class type:" + annotation.annotationType());
    
                Class type = (Class) annotation.annotationType();
    
                /* extract info only for a certain annotation */
                if(type.getName().equals(MyAnnotation.class.getName())) {
    
                     String annotationValue = 
                         (String) type.getMethod("MY_ANNOTATION_CERTAIN_METHOD_NAME").invoke(annotation);
    
                     log.info("annotationValue :" + annotationValue);
                     break;
                }
            }
        }
    
        //do the same for the fields of the class
        for (Field field : myClass.getFields()) {
             //...
        }
    
    }  
    

    To come to this solution, I used the following post: How to get annotation class name, attribute values using reflection

提交回复
热议问题