简体   繁体   中英

Create a proxy object using byte buddy

I am trying to create proxy object using Byte Buddy. I actually want to mock any dependencies in any class and if any method is called on that depended object it will return a per-determined value to the caller.

public class Person{
 private String name;
 private Address address;

 public Person(String name, Address address){
     this.name = name;
     this.address = address;
 }
 public String getAddress(){
  return (address == null) "" : address.getStreet();
 }
}

=======================================================================

public class Address {
  private String street;
  public String getStreet() { return street; }

In this above example I want to mock Address in Person class and whenever person.getAddress() method is invoked. I want to dynamically return a value based on return type. I am new to Byte Buddy. I am able to create a subclass but not sure how to get dynamically return type of the method and return my per-determined value.

Do you have a chance to inject the value provided to the constructor? In this case, you can just create a subclass for Address :

Address address = new ByteBuddy()
  .subclass(Address.class)
  .method(any()).intercept(MethodDelegation.to(MyInterceptor.class))
  .make()
  .load(Address.class.getClassLoader())
  .getLoaded()
  .newInstance();

with a delegate similar to:

public class MyInterceptor {
  @RuntimeType
  public static Object intercept(@Origin Method method) {
    // create some return value or null for void
  }
}

Simply supply this object to the constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM