Java泛型:这里的编译器的问题是什么? (“无唯一最大实例”) [英] Java generics: What is the compiler's issue here? ("no unique maximal instance")

查看:106
本文介绍了Java泛型:这里的编译器的问题是什么? (“无唯一最大实例”)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法:

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

public <T> T fromJson( Reader jsonData, Type clazz ) {
    ...
}

编译器说关于第一种方法:

The compiler is saying about the first method:

 type parameters of <T>T cannot be determined;
 no unique maximal instance exists for type variable T
 with upper bounds T,java.lang.Object

 return fromJson( jsonData, (Type)clazz );
                ^

有什么问题?

推荐答案

问题是第二种方法的定义:

The problem is the definition of the second method:

public <T> T fromJson( Reader jsonData, Type clazz ) {

编译器没有办法告诉什么类型 T 可能有。您必须在此处返回 Object ,因为您不能使用类型< T& 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<T> clazz (Type doesn't support generics).

(T)在第一个方法中会产生警告。要摆脱该警告,您有两个选项:

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. 告诉编译器类型。使用这个(奇数)语法:

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

this.<T>fromJson( jsonData, (Type)clazz );

请注意,您需要 this < T> fromJson()单独是非法语法。

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

使用注释 @SuppressWarnings(unchecked)

这篇关于Java泛型:这里的编译器的问题是什么? (“无唯一最大实例”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆