Je fait en ce moment mumuse avec les nouvelles fonctionnalités de java 1.5.
Voici un des résultat de mes bidouillages.
public interface Allocator<T> {
public T newInstance();
}
public class ClosureAllocator<T> implements Allocator<T> {
private Constructor m_constructor< ? extends T >;
private Object[] m_args;
public ClosureAllocator<T>( Class< ? extends T > clazz, Object ...
args ) {
assert( clazz != null );
Class[] types;
m_args = args.clone();
types = new Class[m_args.length];
for( int i = 0 ; i < m_args.length ; i++ ) {
types[i] = m_args[i].getClass();
}
try {
m_constructor = clazz.getConstructor( types );
assert( Modifier.isPublic(m_constructor.getModifier()) ) :
m_constructor + " is not public.";
} catch( Exception e ) {
assert( false ) : clazz + " has no such a constructor." ;
}
}
public T newInstance() {
try {
return m_constructor.newInstance( m_args );
} catch( Exception e ) {
assert( false ) : e;
}
}
}
// un petit test maintenant
public class AllocatorTest {
public class Test {}
public class Test2 extends Test {}
public class Test3 extends Test {
private String m_string;
public Test3( String s ) {
m_string = s;
}
public String toString() {
return m_string;
}
}
public static void out( Allocator<Test> allocator ) {
for( int i = 0 ; i < 3 ; i++ ) {
System.out.println( allocator.newInstance() );
}
}
public static void main( String[] args ) {
out( new ClosureAllocator<Test>( Test.class ));
out( new ClosureAllocator<Test>( Test2.class ));
out( new ClosureAllocator<Test>( Test3.class, "coucou" ));