如何将泛型类传递给 Java 中的方法?
假设我们有一个函数,可以创建给定特定类的对象:
public static <T> T createObject(Class<T> generic) {
try {
return generic.newInstance();
} catch (Exception ex) {
return null;
}
}
我们可以轻松地使用该函数来创建非泛型类型的实例。
public static void main(String[] args) {
Foo x = createObject(Foo.class);
}
是否可以用泛型类型做同样的事情?
public static void main(String[] args) {
ArrayList<Foo> x = createObject(ArrayList<Foo>.class); // compiler error
}
Suppose we have a function that creates objects given a particular class:
public static <T> T createObject(Class<T> generic) {
try {
return generic.newInstance();
} catch (Exception ex) {
return null;
}
}
We can use the function easily to create instances of non-generic types.
public static void main(String[] args) {
Foo x = createObject(Foo.class);
}
Is it possible to do the same thing with a generic type?
public static void main(String[] args) {
ArrayList<Foo> x = createObject(ArrayList<Foo>.class); // compiler error
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Java 中的泛型是通过类型擦除来实现的。
这意味着
ArrayList
在运行时是一个ArrayList
。编译器只是为您插入强制转换。您可以使用以下方法进行测试:
Generics, in Java, are implemented through type erasure.
That means that an
ArrayList<T>
, at run time, is anArrayList
. The compiler simply inserts casts for you.You can test this with the following:
另外,只要您确定自己在做什么,并且非常确定您的代码不会引起堆污染,您就可以抑制警告。
您还可以考虑到您的代码无法实例化数组,这偶然也需要一个未经检查的异常:
这就是我使用它的方式:
Also, as long as you are sure of what you are doing, and as long as you are pretty sure your code cannot incur heap pollution you can suppress the warning.
You may also take into consideration that your code cannot instantiate arrays, which by chance also requires an unchecked exception:
This is how I used it:
如果您确实需要,您可以强制它进行编译,而不会出现错误或警告:
唯一的问题是在编译时它不能保证
createObject()
不会将对象添加到您的不是
。这对于您的情况可能是安全的,因此您仍然可以获得泛型的好处,而无需求助于使用Foo
类型的 ArrayListArrayList
。If you really need to you can force it to compile without errors or warnings:
The only trouble is that at compile time it can't guarantee that
createObject()
isn't adding objects to yourArrayList
that aren't of typeFoo
. That's probably safe in your case, so you'll still get the benefit of generics without resorting to usingArrayList<?>
.