Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Vector<String>.class vs. Vector.class

Status
Not open for further replies.

cpjust

Programmer
Sep 23, 2003
2,132
US
Hi,
I'm trying to pass the class type to a function and I'm getting an error if I try to pass:
Code:
Func( Vector<String>.class );
but I only get the unchecked warnings if I change it to:
Code:
Func( Vector.class );
How can I pass the proper type Vector<String> to a function?
 
I'm not used to generics but I don't think there's a class for a collection.

Anyway, it sounds a bit strange to me. What are you trying to do? Why passing the variable instead of the class is not enough?

Cheers,
Dian
 
I've had other situations where it would have made my life easier, but today I got bored and started wondering if I could implement C++-style casts instead of the horrible C-style casts that Java uses. This was my first attempt:
Code:
public class Cast<D>
{
	public final static <B> D Dynamic( B  base )
	{
		if ( base instanceof D )
		{
			D d = (D)base;
			return d;
		}

		return null;
	}
}
That failed because of several errors which you can easily find out for yourself. So then I came up with my 2nd (but not as intuitive) attempt:
Code:
public class Cast
{
	public final static <B, D extends B> D Dynamic( Class<D>  derived,
	                                                	   B  base )
	{
		if ( base.getClass().isAssignableFrom( derived ) == true )
		{
			D d = derived.cast( base );
			return d;
		}

		return null;
	}
}
When I tried testing it by passing it a Vector<String>.class as the first parameter, that's when I noticed Java doesn't like that. :-(
 
Generic information is removed at compile time, it's just visible at compile time.
Therefore passing Vector<String>.class is not possible.

Instead of:
Code:
 if (base instanceof D)
{
	D d = (D) base;
	d.foo ();
}
// you could write:
D sampleD = new D ();
D d = Cast.dynamic (sampleD, base);
if (d != null)
{
	d.foo ();
}
I don't see a horrible difference.
If so, than in the second example, where you need an extra sample D, which might often be not that easy to generate.

don't visit my homepage:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top