Java:Instanceof和泛型 [英] Java: Instanceof and Generics

查看:538
本文介绍了Java:Instanceof和泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查看我的通用数据结构中的值索引之前,我想看看它是否是一个这个类型的参数已经被参数化的实例。

Before I look through my generic data structure for a value's index, I'd like to see if it is even an instance of the type this has been parametrized to.

但是Eclipse在我这样做时抱怨:

But Eclipse complains when I do this:

@Override
public int indexOf(Object arg0) {
    if (!(arg0 instanceof E)) {
        return -1;
    }

这是错误讯息:

This is the error message:


无法对类型参数E执行instanceof检查,而是使用它的erasure Object,因为泛型类型信息将在运行时被擦除

有什么更好的方法可以做到这一点?

What is the better way to do it?

推荐答案

在运行时,类型消失了,无法检查它。

The error message says it all. At runtime, the type is gone, there is no way to check for it.

你可以通过为你的对象创建一个工厂来捕获它:

You could catch it by making a factory for your object like this:

 public static <T> MyObject<T> createMyObject(Class<T> type) {
    return new MyObject<T>(type);
 }

然后在对象的构造器存储中输入这样的变量,这样你的方法可能看起来像这样:

And then in the object's constructor store that type, so variable so that your method could look like this:

        if (arg0 != null && !(this.type.isAssignableFrom(arg0.getClass()))
        {
            return -1;
        }

这篇关于Java:Instanceof和泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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