Java,与对象无关的空返回

鉴于 Java 源代码和预处理器(如 C++),我想用返回 null 的函数替换所有提到的 null。它找到对 null 的调用并将其替换为以下函数。


public static Object returnNull(){

    return null;

}

这失败了,因为有不同的类,并且:


functionThatWantsCustomClass( returnNull() ); //Object cannot be converted to CustomClass

或者


if( cc == returnNull() ) //Object cannot be converted to CustomClass

等等。


我能想象的最简单的解决方案是必须对预处理器进行参数化,尽管这需要遍历每个空值以手动添加参数,例如:null/*CustomClass*/.


另一种方法是花费大量时间编写更好的解析器,因此它始终知道 returnTypedNull() 函数所需的类。


有没有办法通过最少的修改/解析来解决这个错误?


慕慕森
浏览 184回答 2
2回答

叮当猫咪

使用泛型:public static <T> T returnNull() {&nbsp; &nbsp; return (T) null;}从评论跟进下面的代码与我所能理解的最接近注释,并且编译得很好:public class Test {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; CustomClass cc = new CustomClass();&nbsp; &nbsp; &nbsp; &nbsp; if (cc != returnNull())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cc.errlog( returnNull() );&nbsp; &nbsp; }&nbsp; &nbsp; public static <T> T returnNull() {&nbsp; &nbsp; &nbsp; &nbsp; return (T) null;&nbsp; &nbsp; }}class CustomClass {&nbsp; &nbsp; void errlog(Exception e) {&nbsp; &nbsp; }}现在,如果有 2 个errlog方法只有一个非原始参数:class CustomClass {&nbsp; &nbsp; void errlog(Exception e) {&nbsp; &nbsp; }&nbsp; &nbsp; void errlog(String s) {&nbsp; &nbsp; }}然后它将失败并显示错误The method errlog(Exception) is ambiguous for the type CustomClass,因为编译器不知道T应该是Exception还是String,即调用两者中的哪一个。您必须明确告诉编译器:cc.errlog( Test.<Exception>returnNull() );

明月笑刀无情

使用泛型蚂蚁它会工作。示例:public class ReturnNullExample {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; ReturnNullExample example = new ReturnNullExample();&nbsp; &nbsp; &nbsp; &nbsp; example.someMethod(ReturnNullClass.returnNull());&nbsp; &nbsp; &nbsp; &nbsp; CustomClass cc = null;&nbsp; &nbsp; &nbsp; &nbsp; if(cc == ReturnNullClass.returnNull()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("cc is null");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; cc = new CustomClass();&nbsp; &nbsp; &nbsp; &nbsp; if(cc != ReturnNullClass.returnNull()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("cc is not null");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public void someMethod(CustomClass customClass) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("This method does nothing");&nbsp; &nbsp; }}class CustomClass {&nbsp; &nbsp; private int number;&nbsp; &nbsp; public int getNumber() {&nbsp; &nbsp; &nbsp; &nbsp; return number;&nbsp; &nbsp; }&nbsp; &nbsp; public void setNumber(int number) {&nbsp; &nbsp; &nbsp; &nbsp; this.number = number;&nbsp; &nbsp; }}class ReturnNullClass {&nbsp; &nbsp; public static <T> T returnNull() {&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java