如果不是基本类型,那么返回 Void
类型的正确方式是什么?例如,我目前使用 null 作为返回值。
interface B<E>{ E method(); }
class A implements B<Void>{
public Void method(){
// do something
return null;
}
}
如果不是基本类型,那么返回 Void
类型的正确方式是什么?例如,我目前使用 null 作为返回值。
interface B<E>{ E method(); }
class A implements B<Void>{
public Void method(){
// do something
return null;
}
}
return (Void)null;
- Alex RJava 8引入了一个新类Optional<T>
,可以在这种情况下使用。要使用它,您需要稍微修改代码如下:
interface B<E>{ Optional<E> method(); }
class A implements B<Void>{
public Optional<Void> method(){
// do something
return Optional.empty();
}
}
这使您能够确保从您的方法中始终获得非空返回值,即使没有任何内容需要返回。当与检测null
是否可以或不能返回的工具结合使用时,特别强大,例如 Eclipse @NonNull
和 @Nullable
注释。
Optional<Void>
是无必要的,因为你总是得到一个空的Optional<Void>
,所以其他所有方法都是没有意义的。这与使用可选值的原因相反。你使用它是因为可能有值,也可能没有值。此外,编译器不能强制实现method()
的正确性。在运行时会出错:return Optional.of(null)
。 - steinybotinterface Action<T> {
public T execute();
}
abstract class VoidAction implements Action<Void> {
public Void execute() {
executeInternal();
return null;
}
abstract void executeInternal();
}
或者您可以省略抽象类,在不需要返回值的每个操作中自己执行 return null。
然后,您可以像这样使用这些操作:
假设有一个方法
private static <T> T executeAction(Action<T> action) {
return action.execute();
}
你可以这样调用
String result = executeAction(new Action<String>() {
@Override
public String execute() {
//code here
return "Return me!";
}
});
executeAction(new VoidAction() {
@Override
public void executeInternal() {
//code here
}
});
当然,为了演示,可以使用反射创建Void
实例:
interface B<E>{ E method(); }
class A implements B<Void>{
public Void method(){
// do something
try {
Constructor<Void> voidConstructor = Void.class.getDeclaredConstructor();
voidConstructor.setAccessible(true);
return voidConstructor.newInstance();
} catch (Exception ex) {
// Rethrow, or return null, or whatever.
}
}
}
你在生产环境中可能不会这样做。
如果更改安全管理器,就可以创建 Void
的实例,像这样:
static Void getVoid() throws SecurityException, InstantiationException,
IllegalAccessException, InvocationTargetException {
class BadSecurityManager extends SecurityManager {
@Override
public void checkPermission(Permission perm) { }
@Override
public void checkPackageAccess(String pkg) { }
}
System.setSecurityManager(badManager = new BadSecurityManager());
Constructor<?> constructor = Void.class.getDeclaredConstructors()[0];
if(!constructor.isAccessible()) {
constructor.setAccessible(true);
}
return (Void) constructor.newInstance();
}
Void
的实例。我发现了获取Void类实例的新方法。这是一个本地代码,其中env
分配了一个Void对象。然后将该对象返回给Java代码。对象存在于Java代码中,并可用作实际实例。
JNIEXPORT jobject JNICALL Java_main_Main_getVoid(JNIEnv *env, jobject obj){
jclass voidclass=env->FindClass("java/lang/Void");
return env->AllocObject(voidclass);
}
没有通用类型可以告诉编译器一个方法不返回任何内容。
我相信惯例是在继承时使用 Object 作为类型参数
或者
将类型参数向上传递,然后让您的类的用户使用 Object 实例化,并将对象分配给使用类型通配符 ?
类型的变量:
interface B<E>{ E method(); }
class A<T> implements B<T>{
public T method(){
// do something
return null;
}
}
A<?> a = new A<Object>();
A<?>
类的用户都无法利用method()
返回的值。 - Christopher Oezbek