T can be either an integer or a char otherwise it should output an error(which is what i want).
My method below is trying to convert the argument from char to int or int to int.
I have no problem if there is no generic and T was int or char but since its not defined, it wont let me compile.
Is there any way to bypass this, or is there another way of converting a generic variable?
Current Code gives error:
incompatible types: T cannot be converted to int
int toReturn = gKey;
public class MyClass<T>{
private int convert(T gKey){
int toReturn = gKey;
return toReturn;
}
}
Edit1: {toReturn instead of 1} I made a mistake and corrected
Edit2: Using the extends Number solution, here are the results that I got
public static void main(String[] args) {
//test 1 for integer argument, should output 1:: success
Test<Integer> test1 = new Test<>();
int a = 1;
System.out.println(test1.convert(a));
//test 2 for character argument, should output 65 :: failure compile error
Test<Character> test2 = new Test<>();
char b = 'A';
System.out.println(test2.convert(b));
}