Writing a generic class

A

allen

Hi,
I'm trying to write a wrapper class for an Object value using generics.
This is a basic example of my problem, my questions are the comments in
the code below:

class Wrapper<T> implements Cloneable
{
private T value = null;

public Wrapper<T> clone( ) throws CloneNotSupportedException
{
// In reality, I need to do some deep cloning of other fields not
// shown here, hence I need to cast the result of super.clone( ).
// How do I cast the following line correctly, to avoid warnings?
// This gives a warning:
Wrapper<T> clone = (Wrapper<T>) super.clone( );
// and this gives an error:
// Wrapper<T> clone = Wrapper<T>.class.cast( super.clone( ) );

return clone;
}

public T getValue( )
{
return value;
}
}
 
G

Gijs Peek

You could just suppress the warning:
....
@SuppressWarnings("unchecked")
public Wrapper<T> clone () throws CloneNotSupportedException
....
since Cloneable doesn't really contain the clone() method. You could also
create a subclass of Cloneable, but that really just moves the problem
 
I

Ian Pilcher

Gijs said:
You could just suppress the warning:
...
@SuppressWarnings("unchecked")
public Wrapper<T> clone () throws CloneNotSupportedException
...

Do you know of a compiler that actually supports the @SuppressWarnings
annotation?
 
T

Thomas Hawtin

Ian said:
Do you know of a compiler that actually supports the @SuppressWarnings
annotation?

Eclipse JDT and Sun's Java SE 6 javac (early access). Also, as a human I
can see the programmer saw and acknowledged the warning (or just hit the
editor's quick fix).

Tom Hawtin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,816
Latest member
SapanaCarpetStudio

Latest Threads

Top