开发者

Generics in Java

开发者 https://www.devze.com 2023-01-11 17:14 出处:网络
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.

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()开发者_C百科;

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

Thank you in advance.


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!
  }
}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消