kerrl
kerrl

Reputation: 11

Generics in Java

Having considered the official Java tutorial and some threads from the past, few things remain unclear and so I'd be glad if someone would explain it to be in plain words.

Class valueClass = agp.getValueClass(); ///the method's return type is Class<?>

if(Double.class.equals(valueClass))
{
...
}

With that my IDE shows me a raw type warning. I've changed the first line to

 Class<?> valueClass = agp.getValueClass();

What other reasonable alternatives do I have and what effects do they bring?

Thank you in advance.

Upvotes: 1

Views: 219

Answers (3)

kerrl
kerrl

Reputation: 11

Thank you all, now I'm clear on that :-)

With

Class<?> 

it can be just any class, even Object itself, whereas with

Class<? extends Object> 

only a subtype of Object (thus not Object itself) is accepted.

Upvotes: 0

Aaron Digulla
Aaron Digulla

Reputation: 328556

My IDE shows me a raw type warning.

You must give your local variable the same type that the method returns. Since the method returns Class<?>, that's what you have to use. There is no way to limit the generic parameter at this point.

Upvotes: 1

f1sh
f1sh

Reputation: 11934

There is one alternative:

Double.class.isAssignableFrom(valueClass)

It does not only check valueClass for equality, but also 'allows' subclasses of Double.


In addition, your agp variable probably holds the value as well. Assuming there is a getValue() method, which probably returns the type Object, you could use instanceof:

if(agp.getValue()!=null){
  if(agp.getValue().getClass() instanceof Double){ //getClass() returns the runtime class
    //it's a (subclass of) Double!
  }
}

Upvotes: 4

Related Questions