Void真的不可以实现吗? [英] Is Void really uninstantiable?

查看:151
本文介绍了Void真的不可以实现吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

javadoc for Void 说:


Void类是一个不可实例化的占位符类,用于保存对表示Java关键字的类对象void。

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

但构造函数只是:

private Void() {}

此代码实例化a Void

Constructor<Void> c = Void.class.getDeclaredConstructor();
c.setAccessible(true);
Void v = c.newInstance(); // Hello sailor

所以 Void not uninstantiable。

So Void is not uninstantiable.

是否有办法让 Void 真正无法实现?

Would there have been a way to make Void truly uninstantiable?

推荐答案

使你的构造函数成为私有,而没有任何其他可以被外部访问的构造函数,使得一个类 un-实例化

Making your constructor private, and not having any other constructor that can be accessed by outside, makes a class un-instantiable.

但是,您无法避免使用 Reflection API 进行访问。使用反射,你可以做,通常不允许的事情。

However, you cannot avoid it from being accessed using Reflection API. Using reflection, you can do, what is not allowed normally.

但是,如果你真的希望你的类不可实现,即使通过 Reflection ,您可以构造函数中抛出 未经检查的异常

But, if you really want your class to be uninstantiable, even through Reflection, you can throw an Unchecked Exception from the constructor.

private MyClass() {
    throw UnsupportedOperationException("Can't instantiate class");
}

在这种情况下,使用创建实例时构造函数#newInstance()方法,它将抛出一个 InvocationTargetException ,@ Alex的评论引用。

In which case, when you create the instance using Constructor#newInstance() method, it will throw an InvocationTargetException, as quoted in comments by @Alex.

这是 构造函数#newInstance() 方法,它声明要抛出的异常列表,其中一个是 InvocationTargetException ,它说: -

Here's the documentation of Constructor#newInstance() method, which declares a list of exception to be thrown, one of them is InvocationTargetException, and it says that: -


throws:
InvocationTargetException - 如果底层构造函数
抛出异常。

throws:
InvocationTargetException - if the underlying constructor throws an exception.

这篇关于Void真的不可以实现吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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