Maven编译jar出现:无法确定 T 的类型参数的异常的原因和处理方案

出错场景:

  代码:

public class JsonUtil {

	private static final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

	public static String toJson(Object obj) {
		return gson.toJson(obj);
	}

	public static <T> T fromJson(String json, Class<T> classOfT) {
		return gson.fromJson(json, classOfT);
	}

	@SuppressWarnings("unchecked")
	public static <T> T fromJson(String json, Type typeOfT) {
		return gson.fromJson(json, typeOfT);
	}
}

  在本地eclipse下编译是没有任何问题。

  maven编译配置:

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>

  异常信息:

[ERROR] 
[ERROR] /opt/web/iwork_shell/release_jar_workspace/831881fe-9cbe-4444-99d9-5667fcb96263/workspace/src/main/java/com/bj58/biz/utility/JsonUtil.java:[26,22] 无法确定 T 的类型参数;对于上限为 T,java.lang.Object 的类型变量 T,不存在唯一最大实例
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException 
英文错误信息:
incompatible types;
found: ........... 
required:...........  

  问题原因:

  用Maven编译,jdk版本已经指定为1.6版,在本地mavan编译打包也一切正常。在maven打包服务器上打包就会出以上的异常信息。发现打包服务器上的jdk版本是jdk1.6.0_16版本,经过查找相关资料确认,该问题是jdk1.6.0_16版本一个bug导致的,这是一个确认的错误:错误号:6468354,具体错误原因可以查看:https://bugs.openjdk.java.net/browse/JDK-6468354

  解决办法:

  1. 在返回的地方加强制类型转换,可以临时绕过该问题

public class JsonUtil {
	private static final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
	public static String toJson(Object obj) {
	  return gson.toJson(obj);
	}
      
	public static <T> T fromJson(String json, Class<T> classOfT) {
	  return (T)gson.fromJson(json, classOfT);
	}

	@SuppressWarnings("unchecked")
	public static <T> T fromJson(String json, Type typeOfT) {
	  return (T)gson.fromJson(json, typeOfT);
	}
}

  2. 升级jdk版本到1.6的最新版本,比如我们升级到jdk1.6.0_38版本后,测试打包就没有问题。根据网上资料,该bug在jdk1.6.0_25版本已经解决(没有亲测吆)

  

原文地址:https://www.cnblogs.com/peida/p/4218210.html