user2071938
user2071938

Reputation: 2255

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?

Upvotes: 1

Views: 1489

Answers (5)

Vishal Zanzrukia
Vishal Zanzrukia

Reputation: 4973

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

Upvotes: 0

Ankur Singhal
Ankur Singhal

Reputation: 26077

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);

Upvotes: 0

Ram&#243;n Gil Moreno
Ram&#243;n Gil Moreno

Reputation: 829

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 () {

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

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

Upvotes: 3

Lrrr
Lrrr

Reputation: 4817

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

Upvotes: 0

Related Questions