创建新的阵列,在GWT类对象 [英] Creating New Array with Class Object in GWT
问题描述
我想创建一个新的阵列,在GWT类对象的特定类型。
I would like to create a new array with a given type from a class object in GWT.
我的意思是,我想效仿的功能
What I mean is I would like to emulate the functionality of
java.lang.reflect.Array.newInstance(Class<?> componentClass, int size)
我需要出现这种情况的原因是,我有一个偶尔需要做到以下几点库:
The reason I need this to occur is that I have a library which occasionally needs to do the following:
Class<?> cls = array.getClass();
Class<?> cmp = cls.getComponentType();
这工作,如果我通常把它传递一个数组类,但我不能动态地创建一些任意组件类型的新数组。
This works if I pass it an array class normally, but I can't dynamically create a new array from some arbitrary component type.
我非常清楚的GWT缺乏反思;我明白这一点。然而,这似乎是可行的,甚至给GWT的有限的反映。相信这样做的原因是,在实施<一href=\"http://$c$c.google.com/p/google-web-toolkit/source/browse/trunk/user/super/com/google/gwt/emul/java/lang/Class.java\" rel=\"nofollow\">http://$c$c.google.com/p/google-web-toolkit/source/browse/trunk/user/super/com/google/gwt/emul/java/lang/Class.java,存在的一个数组创建一个类的对象无法访问的静态方法。
I am well aware of GWT's lack of reflection; I understand this. However, this seems feasible even given GWT's limited reflection. The reason I believe this is that in the implementation http://code.google.com/p/google-web-toolkit/source/browse/trunk/user/super/com/google/gwt/emul/java/lang/Class.java, there exists an inaccessible static method for creating a class object for an array.
同样,我明白阵列的方法仅仅是围绕JavaScript数组类型安全的包装,所以应该很容易破解的,即使需要JSNI。
Similarly, I understand the array methods to just be type-safe wrappers around JavaScript arrays, and so should be easily hackable, even if JSNI is required.
在现实中,更重要的事情会得到类对象,我可以解决不能够做出新的数组。
In reality, the more important thing would be getting the class object, I can work around not being able to make new arrays.
推荐答案
这是我做了类似的事情的方法是传递一个空,长度为0阵列,将希望从创建数组对象的构造函数。
The way that I did a similar thing was to pass an empty, 0 length array to the constructor of the object that will want to create the array from.
public class Foo extends Bar<Baz> {
public Foo()
{
super(new Baz[0]);
}
...
}
巴兹:
public abstract class Baz<T>
{
private T[] emptyArray;
public Baz(T[] emptyArray)
{
this.emptyArray = emptyArray;
}
...
}
在这种情况下,律师类不能直接创建新的T [10],但我们可以做到这一点:
In this case the Bar class can't directly create new T[10], but we can do this:
ArrayList<T> al = new ArrayList<T>();
// add the items you want etc
T[] theArray = al.toArray(emptyArray);
和您得到您的阵列中的一个类型安全的方法。(否则你的电话超(新巴兹[0]);会导致编译器错误)
And you get your array in a typesafe way (otherwise in your call super(new Baz[0]); will cause a compiler error).
这篇关于创建新的阵列,在GWT类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!