Question

First off, I don't think this is necessarily a good idea, I'm just seeing if this is really possible. I could see some benefits, such as not having to explicitly convert to objects that we're sending to the client and using an interface to blacklist certain fields that are security concerns. I'm definitely not stuck on the idea, but I'd like to give it a try.

We're using Spring MVC + Jackson to generate JSON directly from objects. We have our domain object that contains necessary data to send to the client and we have a list of error strings that are added to every outgoing JSON request as needed.

So the return JSON might be something like

{ name: 'woohoo', location : 'wahoo', errors : ['foo'] }

Currently, we have a class that models what should be on the client side, but we always extend a common base class with the error methods.

So, we have:

interface NameAndLoc { 
  String getName(); 
  String getLocation(); 
}

and

interface ResponseErrors { 
  List<String> getErrors(); 
  void appendError(String); 
}

We have two classes that implement these interfaces and would like to have CGLIB generate a new class the implements:

interface NameAndLocResponse extends NameAndLoc, ResponseErrors {}

Presently, with CGLIB mixins, I can generate an object with the following:

Object mish = Mixin.create(
   new Class [] {NameAndLoc.class, ResponseErrors.class},  
   new Object [] { new NameAndLocImpl(), new ResponseErrorsImpl() } );

I could then cast the object to either NameAndLoc or ResponseErrors, however, what I would like to do is create an object that uses the same backing classes, but implements the NameAndLocResponse interface, without having to extend our common error handling class and then implement NameAndLoc.

If I attempt to cast with what I have, it errors out. I'm sure this is possible.

I think it is very similar to this, but not quite: http://www.jroller.com/melix/entry/alternative_to_delegate_pattern_with

Was it helpful?

Solution

Simply add the NameAndLocResponse interface to the Class array in the Mixin constructor as the last argument. The resulting object will implement it. You can find an example of this in this blog entry: http://mydailyjava.blogspot.no/2013/11/cglib-missing-manual.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top