2 回答
TA贡献1776条经验 获得超12个赞
使用泛型:
public static <T> T returnNull() {
return (T) null;
}
从评论跟进
下面的代码与我所能理解的最接近注释,并且编译得很好:
public class Test {
public static void main(String[] args) {
CustomClass cc = new CustomClass();
if (cc != returnNull())
cc.errlog( returnNull() );
}
public static <T> T returnNull() {
return (T) null;
}
}
class CustomClass {
void errlog(Exception e) {
}
}
现在,如果有 2 个errlog方法只有一个非原始参数:
class CustomClass {
void errlog(Exception e) {
}
void errlog(String s) {
}
}
然后它将失败并显示错误The method errlog(Exception) is ambiguous for the type CustomClass,因为编译器不知道T应该是Exception还是String,即调用两者中的哪一个。
您必须明确告诉编译器:
cc.errlog( Test.<Exception>returnNull() );
TA贡献1828条经验 获得超4个赞
使用泛型蚂蚁它会工作。示例:
public class ReturnNullExample {
public static void main(String[] args) {
ReturnNullExample example = new ReturnNullExample();
example.someMethod(ReturnNullClass.returnNull());
CustomClass cc = null;
if(cc == ReturnNullClass.returnNull()) {
System.out.println("cc is null");
}
cc = new CustomClass();
if(cc != ReturnNullClass.returnNull()) {
System.out.println("cc is not null");
}
}
public void someMethod(CustomClass customClass) {
System.out.println("This method does nothing");
}
}
class CustomClass {
private int number;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
class ReturnNullClass {
public static <T> T returnNull() {
return null;
}
}
添加回答
举报