Vous pouvez utiliser cette idée pour corriger le manque de temps de compilation vérifier dans les autres réponses:
import java.lang.reflect.Array;
public class Main
{
public static void main(String[] args)
{
final String[] array;
array = createAndFillArray(String.class, 10, new StringCreator());
for(final String s : array)
{
System.out.println(s);
}
}
public static <T> T[] createAndFillArray(final Class<T> clazz,
final int size,
final Creator<T> creator)
{
T[] result = (T[]) Array.newInstance(clazz, size);
for (int i=0; i<size; i++)
{
result[i] = creator.newInstance();
}
return result;
}
}
interface Creator<T>
{
T newInstance();
}
class StringCreator
implements Creator<String>
{
public String newInstance()
{
// not the best example since String is immutable but you get the idea
// you could even have newInstance take an int which is the index of the
// item being created if that could be useful (which it might).
return ("hello");
}
}
Ceci est en fait plus souple que la façon dont C# vous décrivez puisque vous pouvez contrôler le constructeur si vous voulez plutôt que d'appeler simplement le No-Arg.
qu'est-ce que * où T: new() * fait? – OscarRyz
@Oscar Reyes: 'où T: new()' signifie que 'T' doit avoir un constructeur public sans paramètre. Référence: http://msdn.microsoft.com/en-us/library/d5x73970.aspx –