2012-08-02 2 views
1

클래스가로드되는 동안 클래스에 주석을 추가하려고합니다.
로드 할 때 클래스 바이트 코드를 가져 와서 변경할 수있는 자바 에이전트 변환기를 작성했습니다. 다음 코드를 실행하면 클래스에 새 주석이 표시되지만 이전의 주석과 필드/메서드는 모두 제거됩니다.javassist로 주석을 추가하면 이전 코드가 제거됩니다.

CtClass ctClass = classPool.makeClass(new java.io.ByteArrayInputStream(classFileBuffer)); 
ClassFile classFile = clazz.getClassFile(); 
ConstPool constPool = classFile.getConstPool(); 
AnnotationsAttribute attr= new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag); 
javassist.bytecode.annotation.Annotation annotation = new javassist.bytecode.annotation.Annotation(type, constPool); 
attr.setAnnotation(annotation); 
classFile.addAttribute(attr); 
classFileBuffer = ctClass.toBytecode(); 

여기서 classFileBuffer는 클래스 로더에 반환되는 바이트 배열입니다. 이전 수업의 특수 효과 및 코드가 삭제 된 이유는 누구나 쉽게 이해할 수 있습니다.
감사합니다,
애브너

답변

3

setAnnotation 유형 Annotation입니다 하나의 매개 변수를, 그리고 다른 모든 주석을 지 웁니다. 주석을 기존 기호에 추가하려면 setAnnotations을 대신 사용하십시오. Annotation의 배열을 취하므로 먼저 모든 기존 주석 (getAnnotations 사용)을 모아 배열을 작성한 다음 끝에 Annotation을 추가 한 다음 메소드를 호출하십시오.

setAnnotation(annotation) 호출 setAnnotations(new Annotation[] { annotation })

+0

감사에 해당합니다! 나는 그것을 밖으로 시도 할 것이다. –

관련 문제