废话不多说 直接上代码,如下是修改或者增加RpcFilter实现类上Order注解
程序加载该类前执行代码,如spring可以在org.springframework.boot.SpringApplicationRunListener的contextLoaded方法中
try {
//默认的类搜索路径
ClassPool pool = ClassPool.getDefault();
CtClass ctClass = pool.get(XXXServerFilter.class.getName());
ClassFile classFile = ctClass.getClassFile();
AnnotationsAttribute attributeInfo = new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag);
Annotation annotation = new Annotation(Order.class.getName(), classFile.getConstPool());
MemberValue memberValue = new IntegerMemberValue(classFile.getConstPool(), Integer.MAX_VALUE - 1);
annotation.addMemberValue("value", memberValue);
attributeInfo.addAnnotation(annotation);
classFile.addAttribute(attributeInfo);
reTransformClass(SatelliteHSFServerFilter.class, ctClass.toBytecode());
} catch (Exception e) {
LogUtils.warn(e, "SpringApplicationRunListener.contextLoaded", Maps.newHashMap());
}
private static void reTransformClass(Class<?> clazz, byte[] byteCode) {
ClassFileTransformer cft = (loader, className, classBeingRedefined, protectionDomain, classfileBuffer) -> byteCode;
Instrumentation instrumentation = ByteBuddyAgent.install();
try {
instrumentation.addTransformer(cft, true);
instrumentation.retransformClasses(clazz);
} catch (UnmodifiableClassException e) {
e.printStackTrace();
LogUtils.warn(e,"SpringApplicationRunListener.reTransformClass", Maps.newHashMap());
} finally {
instrumentation.removeTransformer(cft);
}
}
引入包
byte-buddy
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy-agent</artifactId>
<version>1.14.2</version>
</dependency>
javassist
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.21.0-GA</version>
</dependency>