How do I recover the actual type of the this object in a class hierarchy?

Hi,

This is code snippet from Angelica Langer's FAQ:

abstractclass Node <Nextends Node><N>>{

privatefinal List<N> children =new ArrayList<N>();

privatefinal N parent;

protected Node(N parent){

this.parent = parent;

if(parent!=null)

parent.children.add(this);// error: incompatible types

}

public N getParent(){

return parent;

}

public List<N> getChildren(){

return children;

}

}

There are 3 different approaches available in the FAQ to solve this problem.

My question is:

If I write:

...

parent.children.add((N)this);// cast added here

...

as described at the end of this topic in the FAQ, am I safe here (despite

the compilers warning) ? In my opinion, although I understand that

compiler needs to issue a warning, it is actually 100% safe .... or is it not ?

Or let's ask more precise question: can it throw a ClassCastException at

runtime ever ? If so, can you give any example ?

Thanks,

Adrian

[1960 byte] By [AdrianSosialuka] at [2007-11-27 6:16:26]
# 1

You might not get a CCE within the Node class (because of erasure), but maybe on accessing the children, e.g., in a loop, where the cast will be created by the compiler, based on the type information you give to it.

class A extends Node<A> {

public A(A parent) { super(parent); }

}

class B extends Node<A> {

public B(A parent) { super(parent); } // This will add a B as child to an A!

}

...

A a = ...;

B b = new B(a);

for (A anA : b.getChildren()) { ... }

Creating an instance of B will add it as child to a List<A>, which will most probably result in a CCE when looping on the list like shown above, which is type-safe from the compiler point of view.

stefan.schulza at 2007-7-12 17:28:11 > top of Java-index,Core,Core APIs...
# 2

Ohhhh yea !!!!!

The funny thing is that I did exactly what you wrote here and

instead of testing it (with the loop for example ...) I compiled it

and stupidly assumed it was working ! (because I didn't get any

errors).

You really have deep understanding of generics :)

Thanks a lot.

PS. I think you meant:

for(A anA : a.getChildren()) {...}

AdrianSosialuka at 2007-7-12 17:28:11 > top of Java-index,Core,Core APIs...