"instanceof Void"总是返回false吗?

Eng*_*uad 23 java generics instanceof void

这种方法能true以某种方式返回吗?

public static <T> boolean isVoid(T t)
{
    return t instanceof Void;
}
Run Code Online (Sandbox Code Playgroud)

San*_*rma 52

是的,但我确信这不是很有用:

public static void main(final String[] args) throws Exception {
    final Constructor c = Void.class.getDeclaredConstructors()[0];
    c.setAccessible(true);
    System.out.println(c.newInstance(null) instanceof Void);
}
Run Code Online (Sandbox Code Playgroud)

Void类不能被实例化,那么通常你的代码将不要求处理Void的实例.上面的代码片段只是一个例子,说明在使用反射时你可以释放出来的东西...... ;-)

  • +1阻止通过Reflection创建的唯一类是Class. (6认同)
  • 这就是为什么如果你想确保没有人实例化一个类(例如库),你不仅需要使构造函数成为私有,而且还要使构造函数抛出异常.我推荐UnsupportedOperationException. (6认同)
  • +1非常好!顺便说一下,你只需要使用`c.newInstance()`(不需要`null`参数) (2认同)

Yan*_*hon 6

我不明白为什么你会检查一个值是否是void(或Void)的一个实例,因为,就像所说的第n次一样,不能实例化,或者甚至在没有反思的情况下进行扩展.但是,对于更有用的情况,如果您想知道给定Class是否为void类型,则不会使用,instanceof而您的method参数将是类型Class<?>.测试案例将是:

public class VoidCheckTest {

    public static void main(String...args) throws SecurityException, NoSuchMethodException {
        Class<VoidCheckTest> c = VoidCheckTest.class;

        Method m = c.getMethod("main", String[].class);

        System.out.println(m.getReturnType().getName() + " = " + isVoid(m.getReturnType()));        
    }

    private static boolean isVoid(Class<?> t) {
        return Void.class.isAssignableFrom(t) || void.class.equals(t);
    }
}
Run Code Online (Sandbox Code Playgroud)

哪个会输出

void = true
Run Code Online (Sandbox Code Playgroud)

此方法可能还有其他用例,但我现在没有看到任何其他用例.