简体   繁体   中英

java generics <T extends Number>

I have this code:

public class Test<T extends Number>{
   public static void main(String[] args){
       Test<Short> test = new Test(Short.class);
       System.out.println(test.get());
   }
   private Class<T> clazz;
   public Test(Class<T> clazz){
      this.clazz=clazz;
   }
   public T get(){
      if(clazz == Short.class)
          return new Short(13); //type missmatch cannot convert from Short to T
      else return null;
   }
}

but it does not compile... Any Idea how I repair this?

You cannot construct a Short with an int (there is no such constructor), and you could cast to T like

public T get() {
    if (clazz == Short.class)
        return (T) Short.valueOf((short) 13);
    else
        return null;
}

Because your return type is generic T not Short. so you will get type mismatch.

The kind of construction in your code looks more suitable for a non-generics implementation:

Instead of:

public T get() {

Declare it as:

public Number get () {
public T get() {
    if (clazz == Short.class) {
        Short s = 13;
        return (T) s;
    } else {
        return null;
    }
}

Even if you write below, compiler will complain

 Short s = new Short(13); //The constructor Short(int) is undefined

workaround

Short s = new Short((short) 13);

your case

 return (T) new Short((short) 13);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM