我做了一个简单的java项目来测试ByteBuddy。我在Rafael Winterhalter制作的教程中键入了完全相同的代码,但它显示了一些错误
1) ByteBuddyAgent cannot be resolved.
2) type cannot be resolved to a variable.
3) builder cannot be resolved.
4) method cannot be resolved to a variable.
我添加了byte-buddy-1.7.1.jar作为引用库。
public class LogAspect {
public static void main(String[] args){
premain("", ByteBuddyAgent.installOnOpenJDK());
Calculator calculator = new Calculator();
int sum = calculator.sum(10, 15, 20);
System.out.println("Sum is "+ sum);
}
public static void premain(String arg, Instrumentation inst){
new AgentBuilder.Default()
.rebase(type -> type.getSimpleName().equals("Calculator"))
.transform((builder, typeDescription) -> builder
.method(method -> method.getDeclaredAnnotations().isAnnotationPresent(Log.class))
.intercept(MethodDelegation.to(LogAspect.class).andThen(SuperMethodCall.INSTANCE)))
.installOn(inst);
}
public static void intercept(@Origin Method method){
System.out.println(method.getName()+" is called.");
}
}
@interface Log{
}
class Calculator {
@Log
public int sum(int... values) {
return Arrays.stream(values).sum();
}
}