I defined a Java interface to represent the ability of an object to copy itself (no, I don't want to use Cloneable
, but thanks for the suggestion ;-). It's generic:
public interface Copiable<T> {
T copy();
}
An object will only make copies of its own type:
public class Foo implements Copiable<Foo> {
Foo copy() { return new Foo(); }
}
Now, I'm reading Class<?>
objects from a non-generic API (Hibernate metadata, if that is of interest to anyone), and, if they are Copiable
, I want to register them with one of my components. The register
method has the following signature:
<T extends Copiable<T>> register(Class<T> clazz);
My problem is, how do I cast the class before passing it to the method? What I'm currently doing is:
Class<?> candidateClass = ...
if (Copiable.class.isAssignableFrom(candidateClass)) {
register(candidateClass.asSubclass(Copiable.class));
}
This does what I want, but with a compiler warning. And I don't think I'll be able to express the recursive bound in a runtime cast.
Is there a way to rework my code to make it typesafe?
Thanks