Java泛型:比较Object的类到< E> [英] Java Generics: Comparing the class of Object o to <E>
问题描述
假设我有以下类:
public class Test< E> {
?
public boolean sameClassAs(Object o){
// TODO help!
$ / code $ / pre
如何检查
o
与E 测试与LT;字符串> test = new Test< String>();
test.sameClassAs(a string); //返回true;
test.sameClassAs(4); //返回false;
我不能从
(Object o) code>,因为我重写了一个超类,所以不要选择我的方法签名。
我也不想走尝试的道路如果它失败,然后捕获得到的异常。
解决方案
Test的一个实例
没有关于什么E
在运行时的信息。因此,您需要将Class< E>
传递给Test的构造函数。
public class Test< E> {
private final Class< E> clazz中;
public Test(Class< E> clazz){
if(clazz == null){
throw new NullPointerException();
}
this.clazz = clazz;
}
//为了让客户更容易:
public static< T>试验< T> create(Class< T> clazz){
return new Test< T>(clazz);
}
public boolean sameClassAs(Object o){
return o!= null&& o.getClass()== clazz;
$ b如果你想要一个instanceof关系,可以使用Class.isAssignableFrom
而不是Class
比较。请注意,E
需要是非泛型类型,因为Test
需要<$ c $对于Java API中的示例,请参阅java.util.Collections.checkedSet code>和类似的。
Let's say I have the following class:
public class Test<E> { public boolean sameClassAs(Object o) { // TODO help! } }
How would I check that
o
is the same class asE
?Test<String> test = new Test<String>(); test.sameClassAs("a string"); // returns true; test.sameClassAs(4); // returns false;
I can't change the method signature from
(Object o)
as I'm overridding a superclass and so don't get to choose my method signature.I would also rather not go down the road of attempting a cast and then catching the resulting exception if it fails.
解决方案An instance of
Test
has no information as to whatE
is at runtime. So, you need to pass aClass<E>
to the constructor of Test.public class Test<E> { private final Class<E> clazz; public Test(Class<E> clazz) { if (clazz == null) { throw new NullPointerException(); } this.clazz = clazz; } // To make things easier on clients: public static <T> Test<T> create(Class<T> clazz) { return new Test<T>(clazz); } public boolean sameClassAs(Object o) { return o != null && o.getClass() == clazz; } }
If you want an "instanceof" relationship, use
Class.isAssignableFrom
instead of theClass
comparison. Note,E
will need to be a non-generic type, for the same reasonTest
needs theClass
object.For examples in the Java API, see
java.util.Collections.checkedSet
and similar.这篇关于Java泛型:比较Object的类到< E>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!