简体   繁体   中英

Dynamically create an implementation from a class that nearly match the interface?

Say I have this interface:

public interface Foo {
  int getBar();
  String getName();
  // ... 10 other methods
}

And then I have this class, which I can't modify:

public final class FooImpl {
  int getBar();
  String getFirstName(); 
  String getLastName(); 
  // ... 10 other methods which matches Foo
}

I need to use the value from FooImpl to a method that takes Foo. It's easy enough to write a wrapper by hand (eg by anonymous class), which implements Foo and forwards everything to the corresponding method in FooImpl (except for getName() which requires some extra logic from getFirstName and getLastName). Is there a way (preferably from a common library like Guava) to dynamically create such a wrapper given that the requirement that:

  • I want to specify custom logic for one or two method
  • For the rest, just forward to methods with the same name

There is a way. if you create an Object reference of Your interface who contain reference of your class's Object who implement that interface. Then that Object reference able to access those thing.

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