Re: Generics: how to read actual type parameters
- From: Joshua Cranmer <Pidgeot18@xxxxxxxxxxx>
- Date: Sun, 30 Sep 2007 20:07:07 GMT
marek.dudek@xxxxxxxxx wrote:
For example:1. Don't use tabs in Usenet posts.
public class Pair<S> {
public String toString() {
Class clas = ??? ;
return "Pair of " + clas.toString();
}
public S first;
public S second;
}
2. What you are probably intending to do is impossible as specified. There is no possible way at runtime to get the class of S. Java erases the types of the parameters at runtime.
3. Class is generic. Use Class<?> instead.
The easiest thing you can do is:
Class<?> clas = first.getClass();
A potentially tighter bound is:
Class<?> left = first.getClass();
Class<?> right = second.getClass();
Class<?> clas = left;
while (!clas.isAssignableFrom(right))
clas = clas.getSuperclass();
(This returns the last common ancestor of the classes of first and second)
--
Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth
.
- Follow-Ups:
- Re: Generics: how to read actual type parameters
- From: Lew
- Re: Generics: how to read actual type parameters
- From: marek . dudek
- Re: Generics: how to read actual type parameters
- References:
- Generics: how to read actual type parameters
- From: marek . dudek
- Generics: how to read actual type parameters
- Prev by Date: Generics: how to read actual type parameters
- Next by Date: Re: Generics: how to read actual type parameters
- Previous by thread: Generics: how to read actual type parameters
- Next by thread: Re: Generics: how to read actual type parameters
- Index(es):
Relevant Pages
|