在 Java 中,如果转换失败,是否可以尝试转换并返回 null
?
最佳答案
public static <T> T as(Class<T> t, Object o) {
return t.isInstance(o) ? t.cast(o) : null;
}
用法:
MyType a = as(MyType.class, new MyType());
// 'a' is not null
MyType b = as(MyType.class, "");
// b is null
关于c# - 等效于 Java 中的 C# 关键字 'as',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1034204/