你可以编写一个像这样的静态工具方法。我不认为这是非常可读的,但它是你想要做的最好的近似。如果你使用静态导入,它的可读性不会太差。
package com.stackoverflow.examples;
public class Utils {
@SuppressWarnings("unchecked")
public static T safeCast(Object obj, Class type) {
if (type.isInstance(obj)) {
return (T) obj;
}
return null;
}
}这是一个测试案例,演示了它是如何工作的(并且确实起作用)。
package com.stackoverflow.examples;
import static com.stackoverflow.examples.Utils.safeCast;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import org.junit.Test;
public class UtilsTest {
@Test
public void happyPath() {
Object x = "abc";
String y = safeCast(x, String.class);
assertNotNull(y);
}
@Test
public void castToSubclassShouldFail() {
Object x = new Object();
String y = safeCast(x, String.class);
assertNull(y);
}
@Test
public void castToUnrelatedTypeShouldFail() {
Object x = "abc";
Integer y = safeCast(x, Integer.class);
assertNull(y);
}
}