Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

Is there a form of "type safe" casting in Java?

Suppose I have two classes deriving from a third abstract class:

public abstract class Parent{
    public Parent(){
    }
}

public class ChildA extends Parent {
    public ChildA {
    }
}

public class ChildB extends Parent {
    public ChildB {
    }
}

In C# I could handle casting in a somewhat type safe manner by doing:

ChildA child = obj as ChildA;

Which would make child == null if it wasn't a ChildA type object. If I were to do:

ChildA child = (ChildA)obj;

...in C# this would throw an exception if the type wasn't correct.

So basically, is there a way to to do the first type of casting in Java? Thanks.

question from:https://stackoverflow.com/questions/8649975/is-there-a-form-of-type-safe-casting-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I can't think of a way in the language itself, but you can easily emulate it like this:

ChildA child = (obj instanceof ChildA ? (ChildA)obj : null);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...