I ran into a problem when I need to change package information.
package-info.java
@javax.xml.bind.annotation.XmlSchema(namespace = "http://some.url/soap/style/document_literal") package org.example.wsdl.wsdl;
The following code works fine with 1.7.0_45.
// do not load any classes before, this could break the following code. Class<?> pkgInfo = Class.forName("org.example.wsdl.package-info", true, NameSpaceModifier.class.getClassLoader()); Field field = Class.class.getDeclaredField("annotations"); field.setAccessible(true); final XmlSchema oldAnnotation = (XmlSchema) pkgInfo.getAnnotations()[0]; logger.debug("Old Annotation namespace value was: " + oldAnnotation.namespace()); XmlSchema newAnnotation = new XmlSchema() { @Override public XmlNs[] xmlns() { return oldAnnotation.xmlns(); } @Override public String namespace() { return "newNs"; } @Override public XmlNsForm elementFormDefault() { return oldAnnotation.elementFormDefault(); } @Override public XmlNsForm attributeFormDefault() { return oldAnnotation.attributeFormDefault(); } @Override public String location() { return oldAnnotation.location(); } @Override public Class<? extends Annotation> annotationType() { return oldAnnotation.annotationType(); } }; @SuppressWarnings("unchecked") Map<Class<? extends Annotation>, Annotation> annotations = (Map<Class<? extends Annotation>, Annotation>) field.get(pkgInfo); annotations.put(XmlSchema.class, newAnnotation); XmlSchema modifiedAnnotation = (XmlSchema) pkgInfo.getAnnotations()[0];
When compiling and executing the same code with 1.8.0_05, I get this error message:
java.lang.NoSuchFieldException: annotations at java.lang.Class.getDeclaredField(Class.java:2057)
I know him hack, at least he looks like one. But does Java 8 work as expected? How do I change this code that it works with Java 8, then?
Javassist answers are welcome too;)
source share