简体   繁体   中英

Casting with type parameters in java

Say I have a class like this:

class ParameterizedType<T>{
    public boolean equals(Object o){
        if (ParameterizedType<T>.class.isInstance(o)){
            ParameterizedType<T> other = (ParameterizedType<T>) o;
            return this.toString() == other.toString();
        }
        return false;
    }
}

I can get two different warnings from eclipse in such a method.

  1. ParameterizedType<T>.class is not syntactically correct

  2. (ParameterizedType<T>) o is an unchecked cast

How could one get around this?

  1. ParameterizedType<T>.class is not syntactically correct

The reason for this is that with .class you're referring the .class value at Runtime and since Generics is a compile-time feature of Java and the type parameters get erased and replaced with actual type(s), then the statement doesn't make sense at Runtime and the <T> is completely redundant.

Note that the same rule applies for the instanceof operator (ie you can't do if (something instanceof SomeGenericClass<T>) )

  1. (ParameterizedType<T>) o is an unchecked cast

There's no way to compare an Object to ParameterizedType unless downcasting. The IDE correctly suggests that the cast is unchecked, but in order to compare the instances, you have to downcast at some point. In this case, adding a @SuppressWarnings("unchecked") above the method would be fine.

Please also note that Strings in Java should not be compared with ==

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM