Java는 구조 유형 검사를 지원하지 않으므로 Java에서는이 작업을 수행 할 수 없습니다.
스칼라는 그렇지만 적절한 인터페이스를 구현하는 것보다 훨씬 느립니다 (함수 호출을하기 위해 내부적으로 리플렉션을 사용하기 때문에). Scala는 객체 생성자의 형식에 제약 조건을 설정할 수 없습니다. JVM은 형식 지우기를 사용하므로 일반 코드는 실제로 작동중인 유형을 알지 못하므로 어쨌든 해당 유형의 새 객체를 생성 할 수 없습니다.
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");
}
}
이 실제로 당신이 대신하려는 경우 생성자를 제어 할 수 있기 때문에 당신이 설명하는 C#을 방법보다 더 유연 :
* T : new() *는 무엇을합니까? – OscarRyz
@Oscar Reyes :'T : new()'는'T'가 public 매개 변수없는 생성자를 가져야 함을 의미합니다. 참조 : http://msdn.microsoft.com/en-us/library/d5x73970.aspx –