ArrayList<String> list = new ArrayList<String>();
list.add("element");
Generics can be used with jInterflex
interfaces without problems. The
only detail to take into account is that the constructors, which in
our proxy interfaces are written as methods that return the type of the
proxy interface and have a special name, must use the generic types as if
they were static methods in the real class, not constructors.
We will see more clearly this case with an example. Suppose that we
want to call the ArrayList
class with jInterflex
with a code
equivalent to this:
ArrayList<String> list = new ArrayList<String>();
list.add("element");
The part of the ArrayList class which is relevant for us is:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
public ArrayList() {...}
public boolean add(E e) {...}
...
}
If we want to use jInterflex
to call this constructor including
generics we will do:
@JInterflexProxy(realClassName="java.util.ArrayList")
public interface PArrayList<E> {
public static final StaticPart STATIC = JInterflex.proxy(StaticPart.class);
public static interface StaticPart {
public <T> PArrayList<T> ctor();
}
public boolean add(E e);
}
Notice the use of a different type T for the method ctor
, not the same
type E used for the class. Moreover it’s a generic type associated to the
method, not to the interface. This is due to the fact that in jInterflex
we can’t map a constructor in our proxy class to the constructor in the
real class, because we use interfaces and the interfaces don’t have
constructors. The element mapped to the constructor is a method and it’s
not in the same interface as the instance of type E. This
is the only aspect to take into account. With this signature, the call
using Interflex
is easy:
PArrayList<String> list = PArrayList.STATIC.ctor();
list.add("element");
The proxy instances created with jInterflex
are not serializable, even
if the real objects that they represent are serializable. This should
be no problem in the majority of cases, but sometimes it may be necessary to
serialize objects that have a jInterflex
proxy object in an instance field.
The workaround for this situation is to use the real object instead of the
proxy object for the instance field and to use a jInterflex
converter
to obtain the proxy object when its methods or fields must be accessed.