【发布时间】:2020-03-12 10:01:49
【问题描述】:
JDK8和JDK11如何读取java注解的值?
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");
}
}
}
/!\ 实际上,我不知道注解@When 的类型。这可以是 io.cucumber.java 包中的任何接口
结果 JDK8:
---> When I update text {a} with {b}
结果 JDK11(额外引用):(stepAnnotation.toString() 不同!)
---> When "I update text {a} with {b}"
编辑 openjdk11 和 oraclejdk11 不尊重 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>
* @com.acme.util.Name(first=Alfred, middle=E., last=Neuman)
* </pre>
*
* @return a string representation of this annotation
*/
String toString();
【问题讨论】:
标签: java openjdk-11 openjdk-8