views:

307

answers:

4

Edit Since there were many downvotes and people who didn't understand what I'm asking for, I'll rephrase:

How do I find out at runtime what is the class that foo was generified from?

public boolean doesClassImplementList(Class<?> genericClass)
{
  // help me fill this in
  // this method should return true if genericClass implements List
  // I can't do this because it doesn't compile:
  return genericClass instanceof List;
}
A: 

you cannot in Java (type erasure)

dfa
Say what??????? (SO needs at least 15 chars for a comment).
ripper234
A: 

You should be using Class.forName( "fully_qualified_name" ) to generate a Class object, or using the .getClass() method on an already instantiated object. Also, for int types, the class is defined in the Integer.TYPE property.

I need a little more clarification of what you are attempting to do, match the same type? You can use a number of methods, what is the end goal?

Ok, now that you've clarified... heres some help ... just pass in a class..

public boolean doesClassImplementList(Class genericClass)
{
  // help me fill this in
  // this method should return true if genericClass implements List
  // I can't do this because it doesn't compile:

  //this will give you a a list of class this class implements
  Class[] classesImplementing = genericClass.getInterfaces();

  //loop through this array and test for:
  for(int i=0; i<classesImplementing.length; i++) {
   if (classesImplementing[i].getName().equals("java.util.List")) {
    return true;
   }
  }
  return false;
}
Dave Morgan
The questioner does actually use Integer.class in the "question".
Tom Hawtin - tackline
Your answer also works much nicer than mine :)
Dave Morgan
Nice loop. Why didn't you use: List.class.isAssignableFrom(genericClass); instead?Tom - I see no reference to Integer.class in the question.
JeeBee
I hadn't even thought of calling that function - hence why Tom's answer is better.Just shows that there are lots of ways to do the same thing. Of course, some ARE better than others.The Integer.class reference is from before he edited the question.
Dave Morgan
A: 

Class<Integer> is a type declaration, you can't assign it to a variable, as you are doing on your first line.

Class<Integer> is basically a way of referencing the Integer type, so you can pass it as a parameter. It does affect some methods (such as cast) but it is basically a way of providing a generic parameter to a method and associate it with a type.

For example:

public <T> T someMethod(Object someObject, Class<T> castTo) {
     return castTo.cast(someObject);
}
Yishai
+4  A: 

Class.isAssignableFrom

Tom Hawtin - tackline
I get it now, it is really a silly question.I think what confused me is Java's concept of generics. I'm still not quite used to it (as opposed to .Nets').
ripper234