Skip to Main Content

Java Development Tools

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Metaprogramming and generics, how to avoid unchecked cast?

847112Mar 14 2011 — edited Mar 15 2011
I'm working with a class just like this:
abstract class TypeBase<X extends TypeBase<?>>{
	public abstract <Z extends Object> Z toJavaType();
}
This class models a type that could be equivalent to an existing java type.
Generic type Z allows subclasses to return appropriate java type thorugh toJavaType() method.

Few examples of implementations:
class MyIntType extends TypeBase<MyIntType>{
    int i;
    @Override
    public Integer toJavaType() {
        return new Integer(i);
    }
}
class MyDoubleType extends TypeBase<MyDoubleType>{
    double d;
    @Override
    public <Z> Z toJavaType() {
        return (Z)new Double(d);
    }
}
Problem comes here, both implementations generate warning.
The first:
Type safety: The return type Integer for toJavaType() from the type MyIntType needs unchecked conversion to  conform to Z from the type TypeBase<X>
The second:
Type safety: Unchecked cast from Double to Z
Any way to avoid these warnings without using @Suppress("unchecked") annotations?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 12 2011
Added on Mar 14 2011
9 comments
387 views