Java泛型:比较Object的类到< E> [英] Java Generics: Comparing the class of Object o to <E>

查看:324
本文介绍了Java泛型:比较Object的类到< 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 as E?

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 what E is at runtime. So, you need to pass a Class<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 the Class comparison. Note, E will need to be a non-generic type, for the same reason Test needs the Class object.

For examples in the Java API, see java.util.Collections.checkedSet and similar.

这篇关于Java泛型:比较Object的类到&lt; E&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆