we have a use case that might be very well suited for the Reflection Proxy class. Our entity Booking (Interface) has various methods like get, set, add, etc. A concrete implementation is automatically generated and returned after a specific SQL Finder is called (DAO).
Now, there is a need to create another model (read-only) for a different application. The idea is to create a new interface called “NewBooking” that possesses the same get methods as the Booking entity. Our initial idea was to use the Reflection Proxy type. This way, we could avoid making changes to the Booking entity. (which we cant do!) Ideally, only declaring the interface “NewBooking” and using an InvocationHandler to forward the invoked methods of this interface to the corresponding entity would be preferable.
interface Booking {
String getName();
}
class BookingProxy implements InvocationHandler {
private Booking booking;
public BookingProxy(Booking booking) {
this.booking = booking;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(booking, args);
}
}
interface NewBooking {
String getName();
}
public class Main {
public static void main(String[] args) {
Booking realBooking = new BookingImpl(); // some new BookingImpl return by DAO
NewBooking newBookingProxy = (NewBooking) Proxy.newProxyInstance(
NewBooking.class.getClassLoader(),
new Class[] { NewBooking.class },
new BookingProxy(realBooking)
);
System.out.println(newBookingProxy.getName());
}
}
The example code down is something I tried but obviously will throw an ClassCastException.
What might such a solution look like? I think with the example code it gets clear what the intended result is.
Thanks
Kendrick Lmao is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.