Cómo leer el valor de la anotación de Java con JDK8 y JDK11?

sgrillon:

Cómo leer el valor de la anotación de Java con JDK8 y JDK11?

import io.cucumber.java.en.When;

public class Sof {

    private static final Logger log = LoggerFactory.getLogger(Sof.class);

    @When(value = "I update text {string} with {string}(\\?)")
    public static void main(String[] args) {
        Class c = Sof.class;
        Method[] methods = c.getMethods();
        Method method = null;
        for (Method m : methods) {
            if (m.getName().equals("main")) {
                method = m;
            }
        }
        Annotation stepAnnotation = method.getAnnotation(When.class);
        Object as[] = { "a", "b" };
        Matcher matcher = Pattern.compile("value=(.*)\\)").matcher(stepAnnotation.toString());
        if (matcher.find()) {
            log.info("---> " + stepAnnotation.annotationType().getSimpleName() + " " + String.format(matcher.group(1).replaceAll("\\{\\S+\\}", "{%s}").replace("(\\?)", ""), as));
        } else {
            System.err.println("error");
        }
    }

}

/! \, En realidad, no sé el tipo de anotación @When. esto puede ser cualquiera de las interfaces en el paquete io.cucumber.java

como resultado JDK8:

---> When I update text {a} with {b}

como resultado JDK11 (cotización adicional): ( stepAnnotation.toString()es diferente!)

---> When "I update text {a} with {b}"

EDITAR openjdk11 y oraclejdk11no respetan javadoc:

/**
 * Returns a string representation of this annotation.  The details
 * of the representation are implementation-dependent, but the following
 * may be regarded as typical:
 * <pre>
 *   &#064;com.acme.util.Name(first=Alfred, middle=E., last=Neuman)
 * </pre>
 *
 * @return a string representation of this annotation
 */
String toString();
Wim Deblauwe:

Usted no debe depender de la toString()aplicación que normalmente es para depurar / registro únicamente.

Ver ¿Es posible leer el valor de una anotación en Java? para más detalles sobre cómo leer el valor de una anotación.

ACTUALIZAR:

Para hacer todo a través de la reflexión, que puede así que algo como esto:

import org.springframework.transaction.annotation.Transactional;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;

public class AnnotationTest {
    public static void main(String[] args) throws IllegalAccessException, InvocationTargetException {
        Method[] methods = AnnotationTest.class.getMethods();
        System.out.println("methods = " + Arrays.toString(methods));
        for (Method method : methods) {
            System.out.println("method = " + method);
            Annotation[] annotations = method.getAnnotations();
            System.out.println("annotations = " + Arrays.toString(annotations));

            for (Annotation annotation : annotations) {
                System.out.println("annotation = " + annotation);

                Class<? extends Annotation> annotationClass = annotation.annotationType();
                System.out.println("annotationClass = " + annotationClass);
                Method[] annotationMethods = annotationClass.getMethods();
                System.out.println("annotation methods = " + Arrays.toString(annotationMethods));
                for (Method annotationMethod : annotationMethods) {
                    if (Modifier.isPublic(annotationMethod.getModifiers())) {
                        String name = annotationMethod.getName();
                        Object o = annotationMethod.invoke(annotation);
                        System.out.println(name + ": " + o);
                    }

                }
            }
        }
    }

    @Transactional("bla")
    public void test() {
    }
}

(Utilicé una de las anotaciones de la primavera aquí, ya que eso es lo que sucede que tiene en mi ruta de clase)

ACTUALIZACIÓN (con el extremo de solución):

@When(value = "I update text {string} with {string}(\\?)")
public static void main(String[] args) {
    Object as[] = { "a", "b" };
    Class c = Sof.class;
    Method[] methods = c.getMethods();
    Method method = null;
    for (Method m : methods) {
        if (m.getName().equals("main")) {
            method = m;
        }
    }
    Annotation stepAnnotation = method.getAnnotation(When.class);
    Class<? extends Annotation> annotationClass = stepAnnotation.annotationType();
    try {
        Method valueMethods = annotationClass.getDeclaredMethod("value");
        if (Modifier.isPublic(valueMethods.getModifiers())) {
            log.info("---> {} " + String.format(valueMethods.invoke(stepAnnotation).toString().replaceAll("\\{\\S+\\}", "{%s}").replace("(\\?)", ""), as),
                    stepAnnotation.annotationType().getSimpleName());
        }
    } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
        e1.printStackTrace();
    }
}

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=275818&siteId=1
Recomendado
Clasificación