如何在java项目中使用ByteBuddy

时间:2017-07-26 15:55:35

标签: byte-buddy

我做了一个简单的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();
}

}

1 个答案:

答案 0 :(得分:0)

看起来你正在使用一个非常过时的0. * ara教程。使用IDE检查编译时错误,并使用check the webpage查看更新的教程。