Using a generic to cast, and then ? [T s = (T)new Stuff()]

  • Thread starter Sébastien de Mapias
  • Start date
S

Sébastien de Mapias

Hi,
What are the limitations of using a cast with a generic ?
How *beautiful* would it be if I could write a generic 'equals()'
method -for exple-, with the following:

public class StuffImpl extends GenericTypes<StuffImpl>
{
// almost empty class...
}

public abstract class GenericTypes<T>
{
...
private String value;
...
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
// final StuffImpl other = (StuffImpl) obj;
final T other = (T) obj;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}

This equals is that generated by RAD. Once I do
final T other = (T) obj;
the jdk complains on the line
if (other.value != null)
saying it "cannot find symbol"...

Too bad isn't it ?

Has someone perhaps found a way to implement an "equals()"
method similar to that above, using a casted generic ?

What operations are possible on 'other' (I mean using Class.forName()
etc.) to try to retrieve what 'other' really is, what instanceOf it
is ??

The possibilities seem to be much lesser than with C++ don't they ?

In advance, many thanks.
Regards,
Sébastien
 
S

Sébastien de Mapias

What operations are possible on 'other' (I mean using Class.forName()
etc.) to try to retrieve what 'other' really is, what instanceOf it
is ??

Using reflection maybe ?
 
L

Lew

Sébastien de Mapias said:
This equals is that generated by RAD. Once I do
  final T other = (T) obj;
the jdk complains on the line
  if (other.value != null)
saying it "cannot find symbol"...

Too bad isn't it ?

Not at all. The problem would be if it accepted that. How should the
compiler determine that type T has a member named 'value'? You have
given it no indication that it does. You have declared that the type
*GenericTypes* has such a member, but not T.

Also, you really cannot cast on a generic parameter type. You don't
show an @SuppressWarnings() annotation, so presumably the cast raised
you a compiler warning.
 

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

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top