有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java的泛型和实例

好的,这是我的类,它封装了一个对象,并将等于和字符串委托给这个对象,为什么我不能使用???的实例

public class Leaf<L>
{
    private L object;

    /**
     * @return the object
     */
    public L getObject() {
        return object;
    }

    /**
     * @param object the object to set
     */
    public void setObject(L object) {
        this.object = object;
    }

    public boolean equals(Object other)
    {
        if(other instanceof Leaf<L>) //--->ERROR ON THIS LINE
        {
            Leaf<L> o = (Leaf<L>) other;
            return this.getObject().equals(o.getObject());
        }
        return false;
    }

    public String toString()
    {
        return object.toString();
    }
}

我怎样才能让它工作?? 谢谢


共 (3) 个答案

  1. # 1 楼答案

    我也遇到了类似的问题,通过如下方式使用反射来解决:

    public class Leaf<L>
    {
        private L object;
    
        /**
         * @return the object
         */
        public L getObject() {
            return object;
        }
    
        /**
         * @param object the object to set
         */
        public void setObject(L object) {
            this.object = object;
        }
    
        public boolean equals(Object other)
        {
            if(other instanceof Leaf) // ->Any type of leaf
            {
                Leaf o = (Leaf) other;
                L t1 = this.getObject();   // Assume it not null 
                Object t2 = o.getObject(); // We still not sure about the type
                return t1.getClass().isInstance(t2) && 
                   t1.equals((Leaf<L>)t2); // We get here only if t2 is same type
            }
            return false;
        }
    
        public String toString()
        {
            return object.toString();
        }
    }
    
  2. # 2 楼答案

    泛型信息实际上在编译时被删除,在运行时不存在。这就是所谓的类型擦除。在引擎盖下,你所有的叶子对象实际上都相当于叶子<;对象>;并在必要时添加其他类型

    因此,运行时无法区分Leaf<;Foo>;和叶<;酒吧>;因此不可能进行瞬间测试