泛型实现理解?

时间:2014-01-10 12:00:54

标签: java generics reflection

我是Generics和Reflection的新手。你能否告诉我下面代码中发生了什么?

public static <T extends SomeObject> T returnObject(Class<T> classOfT, SomeClass data) throws SomeException
{

T object= null; 
Class[] signature = new Class[] {SomeClass.class};
        Object[] args = new Object[] {data};
Constructor<T> objectConstructor = classOfT.getDeclaredConstructor(signature);
object= (T)objectConstructor.newInstance(args);

}

1 个答案:

答案 0 :(得分:4)

// The T must extend SomeObject wherever it appears. This method returns a T, you call it specifying a class T. i.e. X returnObject(Class<X>. SomeClass data is a normal param
public static <T extends SomeObject> T returnObject(Class<T> classOfT, SomeClass data) throws SomeException
{
    // Create a new reference to an object of the generic type initialized to null
    T object= null; 
    // Create arrays holding the class and the data passed in as SomeClass data
    Class[] signature = new Class[] {SomeClass.class};
    Object[] args = new Object[] {data};
    // Use reflection on the Class of T to find a constructor that matches data
    Constructor<T> objectConstructor = classOfT.getDeclaredConstructor(signature);
    // Call that constructor passing in the value given
    object= (T)objectConstructor.newInstance(args);
}

基本上,这是一个非常长篇大论的说法:

X x = new X(data);

除非有更多内容,否则整个功能似乎毫无意义。