有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java,treque,用类t实例化数组

我有一个具有构造函数的类

public Treque(Class<T> t) {

}

我需要实例化一个具有类t的数组。如何实例化它


共 (1) 个答案

  1. # 1 楼答案

    这取决于你的确切目标是什么。如果你想要一些武断的东西,那就去反思吧。如果只想传递一个继承类的对象,可以使用不同的语法

    由于您的示例使用类,请尝试以下反射示例:

    我想这里公认的答案就是你想要的Java Generics Creating Array from Class

    还有一点:

        public void test(Class<T> t) {
                T[] a=new T[10];//complie error
    
            Object array = java.lang.reflect.Array.newInstance(t, 10);//lots of ambiguity
            String[] arrT = (String[]) array;//works if you know the final type
    
            Object[] anyType = new Object[10];
            for(int i=0;i<10;i++)
                   anyType[i] = createObject(t.getName());
            //You will need to cast the Object to your desired type
            }
          static Object createObject(String className) {
              //http://www.java2s.com/Code/Java/Reflection/ObjectReflectioncreatenewinstance.htm
          Object object = null;
          try {
              Class classDefinition = Class.forName(className);
              object = classDefinition.newInstance();
          } catch (InstantiationException e) {
              System.out.println(e);
          } catch (IllegalAccessException e) {
              System.out.println(e);
          } catch (ClassNotFoundException e) {
              System.out.println(e);
          }
          return object;
       }