等效于 Java 中的 C# 关键字“as”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1034204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Equivalent of the C# keyword 'as' in Java
提问by shoosh
In Java, is it possible to attempt a cast and get back null
if the cast fails?
在 Java 中,是否可以尝试转换并null
在转换失败时返回?
采纳答案by erickson
public static <T> T as(Class<T> t, Object o) {
return t.isInstance(o) ? t.cast(o) : null;
}
Usage:
用法:
MyType a = as(MyType.class, new MyType());
// 'a' is not null
MyType b = as(MyType.class, "");
// b is null
回答by Eugene Ryzhikov
You can use the instanceof
keyword to determine if you can cast correctly.
您可以使用instanceof
关键字来确定是否可以正确投射。
return obj instanceof String?(String)obj: null;
Of course it can be genericied and made into the function, but I think question was about what means Java have to accomplish this.
当然,它可以被泛化并制作成函数,但我认为问题是 Java 必须通过什么方式来实现这一点。
回答by Peter
AFAIK, this would be (one) of the ways to do that:
AFAIK,这将是(一种)方法:
SomeClassToCastTo object = null;
try {
SomeClassToCastTo object = SomeClassToCastTo.class.cast(anotherObject);
}
catch (ClassCastException e) {
object = null;
}
Ugly, but it should do what you want...
丑陋,但它应该做你想做的......
回答by neesh
In Java if a cast fails you will get a ClassCastException. You can catch the exception and set the target object to null.
在 Java 中,如果转换失败,您将收到 ClassCastException。您可以捕获异常并将目标对象设置为 null。
回答by Rony
you can handle this catching ClassCastException
你可以处理这个捕获 ClassCastException
回答by Pesto
You can either catch the exception:
您可以捕获异常:
Foo f = null;
try {
f = Foo(bar);
}
catch (ClassCastException e) {}
or check the type:
或检查类型:
Foo f = null;
if (bar instanceof Foo)
f = (Foo)bar;
回答by Kathy Van Stone
You can, but not with a single function in Java:
您可以,但不能使用 Java 中的单个函数:
public B nullCast(Object a) {
if (a instanceof B) {
return (B) a;
} else {
return null;
}
}
EDIT: Note that you can't make the B class generic (for this example) without adding the target class (this has to do with the fact that a generic type is not available to instanceof
):
编辑:请注意,您不能在不添加目标类的情况下使 B 类泛型(对于此示例)(这与泛型类型不可用于 的事实有关instanceof
):
public <V, T extends V> T cast(V obj, Class<T> cls) {
if (cls.isInstance(obj)) {
return cls.cast(obj);
} else {
return null;
}
}
回答by OscarRyz
MyType e = ( MyType ) orNull( object, MyType.class );
// if "object" is not an instanceof MyType, then e will be null.
...
...
public static Object orNull( Object o , Class type ) {
return type.isIntance( o ) ? o : null;
}
I guess this could somehow done with generics also but I think but probably is not what is needed.
我想这也可以用泛型来完成,但我认为但可能不是所需要的。
This simple method receives Object and returns Object because the cast is performed in the method client.
这个简单的方法接收 Object 并返回 Object,因为转换是在方法客户端中执行的。
回答by Harold L
The two solutions above are somewhat awkward:
上面的两个解决方案有点尴尬:
Casting and catching ClassCastException: creating the exception object can be expensive (e.g. computing the stack trace).
投射和捕获 ClassCastException:创建异常对象可能很昂贵(例如计算堆栈跟踪)。
The nullCast method described earlier means you need a cast method for each cast you want to perform.
前面描述的 nullCast 方法意味着您需要为每个要执行的强制转换设置一个强制转换方法。
Generics fail you because of "type erasure" ...
由于“类型擦除”,泛型使您失败......
You can create a static helper method that is guaranteed to return an instance of your target class or null, and then cast the result without fear of exception:
您可以创建一个静态帮助器方法,该方法保证返回目标类的实例或 null,然后将结果强制转换而不必担心异常:
public static Object nullCast(Object source, Class target) {
if (target.isAssignableFrom(source.getClass())) {
return target.cast(source);
} else {
return null;
}
}
Sample call:
示例调用:
Foo fooInstance = (Foo) nullCast(barInstance, Foo.class);