如何在 Java 中模拟 C# as-operator [英] How to emulate C# as-operator in Java

查看:20
本文介绍了如何在 Java 中模拟 C# as-operator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,让类型转换返回空值而不是抛出 ClassCastException 是可行的.C# 有 as 运算符来执行此操作.Java 中是否有可用的等效项,因此您不必显式检查 ClassCastException?

There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the as operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException?

推荐答案

这是 @Omar Kooheji 建议的 as 实现:

Here's an implementation of as, as suggested by @Omar Kooheji:

public static <T> T as(Class<T> clazz, Object o){
    if(clazz.isInstance(o)){
        return clazz.cast(o);
    }
    return null;
}

as(A.class, new Object()) --> null
as(B.class, new B())  --> B

这篇关于如何在 Java 中模拟 C# as-operator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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