我目前需要更改java.lang.reflect.Method对象的注释,该对象应该是原始方法的一个克隆,这样原始的方法就不会被修改。为此,我下载了Library Javassist。因此,基本上,这样做的最佳代码是:
java.lang.reflect.Method myMethod = /*obtain it*/;
java.lang.reflect.Method myMethodClone = myMethod.clone();
myMethodClone.removeAllAnnotations();
myMethodClone.addAnnotation("@MyAnnotation(something=\"something\", etc");
但是不幸的是,类似于此伪代码的代码是不可能的。我尝试使用javassist解决问题,但是随后遇到了另一个问题:我无法将Javassists的CtMethod对象转换为方法对象,至少在不更改原始方法所在的类的情况下,这是无法做到的。
有人知道如何解决这个问题吗?
我设法通过使用默认的Java Annotation&Method类加上一些反射使代码正常工作。这是我的操作方法(由于我的问题很具体,可能无法帮助任何人,但是您永远不会知道...)(伪代码):
//Create Annotation
MyAnnotationOld oldAnnotation;
MyAnnotation modifiedAnnotation = new MyAnnotation{
public Class<? extends java.lang.annotation.Annotation> annotationType() {return oldAnnotation.annotationType();}
public String propertyWhichShallRemainTheSame() {return oldAnnotation.propertyWhichShallRemainTheSame();}
public String propertyWhichShallBeModified() {return "Modified Thingy";}
}
//Copy Method
Method toCopy;
Method copyMethod = Method.class.getDeclaredMethod("copy", (Class<?>[])null);
copyMethod.setAccessible(true);
Method copiedMethod = (Method) copyMethod.invoke(toCopy, (Object[]) null);
//Add annotation to copied method
Field field = Method.class.getDeclaredField("declaredAnnotations");
field.setAccessible(true);
//Intantiate field !!IMPORTANT!! If you don't do this, the field will be null and thus return an error.
copiedMethod.getAnnotations();
Map<Class<? extends Annotation>, Annotation> annotations = (Map<Class<? extends Annotation>, Annotation>) field.get(copiedMethod);
annotations.put(MyAnnotation.class, modifiedAnnotation);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句