質問

ClassCastExceptionをスローする代わりに、型キャストがnull値を返すことが実用的である状況があります。 C#には、これを行う as 演算子があります。 Javaで利用可能な同等のものがあるので、ClassCastExceptionを明示的に確認する必要はありませんか?

役に立ちましたか?

解決

@Omar Koohejiが示唆するasの実装は次のとおりです。

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

他のヒント

あなたはあなた自身を転がさなければならないと思います:

return (x instanceof Foo) ? (Foo) x : null;

編集:クライアントコードでnullを処理したくない場合は、 Nullを導入できますオブジェクト

interface Foo {
    public void doBar();
}
class NullFoo implements Foo {
    public void doBar() {} // do nothing
}
class FooUtils {
    public static Foo asFoo(Object o) {
        return (o instanceof Foo) ? (Foo) o : new NullFoo();
    }
}
class Client {
    public void process() {
        Object o = ...;
        Foo foo = FooUtils.asFoo(o);
        foo.doBar(); // don't need to check for null in client
    }
}

C#の is の代わりに instanceof キーワードを使用できますが、 as のようなものはありません。

例:

if(myThing instanceof Foo) {
   Foo myFoo = (Foo)myThing; //Never throws ClassCastException
   ...
}

このような静的ユーティリティメソッドを記述できます。私はそれがひどく読みやすいとは思わないが、あなたがやろうとしていることの最良の近似である。また、静的インポートを使用する場合、読みやすさの点でそれほど悪くはありません。

package com.stackoverflow.examples;
public class Utils {
    @SuppressWarnings("unchecked")
    public static <T> T safeCast(Object obj, Class<T> 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);
    }
}

Java 8では、オプションでストリーム構文を使用することもできます:

Object o = new Integer(1);

Optional.ofNullable(o)
        .filter(Number.class::isInstance)
        .map(Number.class::cast)
        .ifPresent(n -> System.out.print("o is a number"));

as演算子として適切に折り目を付けることができると推測しています

次のようなもの

as<T,Type> (left, right)  
which evaluates to 
if (typeof(left) == right)
   return (right)left
else
    return null

どうやってやるかわからない、私は現時点でc#であり、大学を卒業してからJavaの帽子が少し埃っぽくなった。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top