简体   繁体   中英

Wrapping a class without repeating all methods in Java

I want to write a Java class that wraps another class in a specific way for a multi-tenant system:

  • All methods of the original class should exist in the new class
  • Except that arguments of the new methods should be the same minus 1: the tenant (=current user)
  • I want to write as little code as possible for the new class. In the best case it should be empty and have all methods "auto-generated" or "auto-detected" at runtime.

Example:

Take this existing class:

MyService{
   public List<Product> getProducts(Account filterWithUseraccount);
   public List<Purchase> getPurchases(Account filterWithUseraccount, Date fromDate, Date tillDate);
   public List<Category> getCategories(Account filterWithUseraccount, Category parentCategory);
}

And I want to create this new class, but the methods should be "auto-generated":

MyTenantOrientedService{

   // Assign an account which will be used to call all MyService methods
   private Account filterWithUseraccount;

   // The service being wrapped
   private MyService myService;

   public List<Product> getProducts(){
      return myService.getProducts(filterWithUseraccount);
   }
   public List<Purchase> getPurchases(Date fromDate, Date tillDate){
      return myService.getPurchases(filterWithUseraccount, fromDate, tillDate);
   }
   public List<Category> getCategories(Category parentCategory){
      return myService.getCategories(filterWithUseraccount, parentCategory);
   }
}

As you can see, the methods in MyTenantOrientedService are the same as in MyService, except that the parameter "Account filterWithUseraccount" is never used and can be taken from the private property.

This is a simple example, but imagine a class with a lot of methods, making it a huge chore to create the wrapping functions. This is a lot of code duplication and bug can easily be created.

I believe a solution might exist using AOP or other design pattern, but I can't figure out which.

Your IDE handles this kind of tasks for you.

For example, you could add a member variabile of type MyService inside MyTenantOrientedService and, on Eclipse, right-click on MyTenantOrientedService, then click on "Source -> Generate Delegate Methods"

It is applying the Delegation Pattern for you.

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