Java generics: What is the compiler's issue here? (“no unique maximal instance”)

前端 未结 4 2007
轻奢々
轻奢々 2021-02-20 17:41

I have the following methods:

public  T fromJson( Reader jsonData, Class clazz ) {
    return fromJson( jsonData, (Type)clazz );
}

public <         


        
4条回答
  •  暖寄归人
    2021-02-20 18:21

    The problem is the definition of the second method:

    public  T fromJson( Reader jsonData, Type clazz ) {
    

    There is no way for the compiler to tell what type T might have. You must return Object here because you can't use Type clazz (Type doesn't support generics).

    This leads to a cast (T) in the first method which will cause a warning. To get rid of that warning, you have two options:

    1. Tell the compiler the type. Use this (odd) syntax:

      this.fromJson( jsonData, (Type)clazz );
      

      Note that you need the this here because fromJson() alone is illegal syntax.

    2. Use the annotation @SuppressWarnings("unchecked").

提交回复
热议问题