Search code examples
javagenericscompilationjavacerror-suppression

Compiling these lines in Java - possible in any way?


its about compiling this method, where T is generic. Is there a way to compile this with the javac Compiler (Java 1.8) without getting any error?

public class MyGenericClass<T>{
    public void someGenericAction(T value){
        int key = (int) value;
    }
}

Best regards from Germany!


Solution

  • You can do this

    class MyGenericClass<T>{
            public static <T>void someGenericAction(T value){
                int key = (Integer)value; // here is your's
                System.out.println(key);
            }
    
            public static void main(String[] args){
                someGenericAction(12);
            }
    }