如何从传递给函数的列表T []中获取泛型T的类型,然后使用T进行实例化?

时间:2018-09-06 07:00:29

标签: java

例如,假设有一段代码如下:

public className<T> {
    public className(T[] varName) {
        //somecode
    }
}

我如何从T []的实例中获取T的类型,然后使用它实例化T类型的对象?

1 个答案:

答案 0 :(得分:0)

在这种情况下,为了使您能够实例化类型为T的任何元素,您将需要使用反射并且还必须满足一些条件:

  • 如果数组不为空并且数组中至少有一个元素,则只能获取import javax.swing.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class TypeClass<T> { public TypeClass(T[] array) throws IllegalAccessException, InvocationTargetException, InstantiationException { if(array != null && array.length > 0) { // You can only get the type of T if the arrays is not null and there is at least one element in the array T first = array[0]; Class<?> clazz = first.getClass(); Constructor<?>[] constructors = clazz.getConstructors(); for(Constructor<?> constructor : constructors) { int parameterCount = constructor.getParameterCount(); // Check if the constructor has a no args argument if(parameterCount == 0) { T o = (T) constructor.newInstance(); // Do something with the new object System.out.println(o); } } } } public static void main(String[] args) throws IllegalAccessException, InstantiationException, InvocationTargetException { JFrame[] jframes = new JFrame[]{new JFrame()}; TypeClass<JFrame> typeClass = new TypeClass<>(jframes); } } 的类型。由于类型擦除,在数组中不存在实际对象的情况下,无法直接推断类型。

  • 然后,您必须检查数组中第一个对象的构造函数是否没有参数。

这是一个可执行的示例,您可以在下面试用:

javax.swing.JFrame[frame0,0,0,0x0,invalid,hidden,layout=java.awt.BorderLayout,title=,resizable,normal,defaultCloseOperation=HIDE_ON_CLOSE,rootPane=javax.swing.JRootPane[,0,0,0x0,invalid,layout=javax.swing.JRootPane$RootLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true]

如果运行此命令,您将在控制台中看到以下内容:

T

更新

您还可以指定一个替代构造函数,该构造函数专门指示要通过反射实例化的类型。这更有意义,因为数组中元素的类型实际上可能是类型// Alternative with the specific type for instantiation public TypeClass(T[] array, Class<T> tClass) throws IllegalAccessException, InvocationTargetException, InstantiationException { if(tClass != null) { Class<?> clazz = tClass.getClass(); Constructor<?>[] constructors = clazz.getConstructors(); for(Constructor<?> constructor : constructors) { int parameterCount = constructor.getParameterCount(); // Check if the constructor has a no args argument if(parameterCount == 0) { T o = (T) constructor.newInstance(); // Do something with the new object System.out.println(o); } } } } 的子类。这是替代构造函数的示例:

componentDidUpdate(prevProps, prevState, snapshot) {
    if(prevProps.currentIndustry !== this.props.currentIndustry) {
        console.log('not matched'); // only logged if condition meets
        this.getMainProductGroups();
    }
}
相关问题