Is there a clean way to assign the Class of a generic type to a variable?

后端 未结 2 758
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-19 17:44

Given this code:

List ints = new ArrayList();

// Type mismatch: 
// cannot convert from Class t         


        
相关标签:
2条回答
  • 2021-02-19 18:07

    This is a real Catch-22 in Java.

    The compiler warns you if you don't add a generic type to List:

    // WARN: List is not typed
    Class<? extends List> typeTry3 = ints.getClass();
    

    That's because, in most cases, it's really best to type your Lists.

    However, because of type erasure, there's no way for Java to figure out the generic type of List at runtime, and the compiler knows that. Therefore, there is no method on Class that will returned a typed object:

    // ERROR: ints.getClass() doesn't return a Class<List<Integer>>, it returns a Class<List>
    Class<? extends List<? extends Integer>> var = ints.getClass();
    

    So you must cast it to a typed list. However, as you know, since there is no runtime type checking, Java warns you about any casts to a typed variable:

    // WARN: Casting to typed List
    Class<List<Integer>> typeTry2 = (Class<List<Integer>>) ints.getClass();
    

    Any attempt to get around this is essentially a means of confusing the compiler, and will inevitably be convoluted.

    Your best bet then is to go with Option B:

    On the other hand, if warning suppression is the only way, what is the safest to suppress?

    The safest way to suppress this warning is to make your @SuppressWarnings("unchecked") annotation as localized as possible. Put them above each individual unchecked cast. That way it's absolutely clear who's causing the warning.

    0 讨论(0)
  • 2021-02-19 18:21

    One way to do this would be to create your own class. I am not sure if this would meet your needs.

    I am not really sure what you are trying to achieve. So perhaps wildcards is the answer.

    import java.util.*;
    
    class Main
    {
          public static void main(String[] args)
          {
                List<Integer> list = new ArrayList<Integer>();
                Class<?> clazz = list.getClass();
                System.out.println(clazz) ;
          }
    }
    
    0 讨论(0)
提交回复
热议问题