开发者

Dynamic Casting:

It seems so obvious. How can I cast an object myObjet to the type of myObjet.getClass ? I tried combinations of forName(), cast and others ... none seem to work :s

The problem is that I have a list of Objects and I would like to get them back to their original type (which is given by myObjet.getClass.getName()).

Regards, Tim


Yes this is Java and it is certainly not wrong. Let me explain the problem. Picture a program that deals with simple forms like Squares and Circles that are derived classes from Form, the main class.

So there is a search function that returns a Form, but you have to provide the type an开发者_运维技巧d a reference of the form (a number, for example):

Form myForm= searchForm(String formType, String formRef)

I know what the Form it returns is going to be because I gave those arguments to the search function: a square, for instance. The returned object will still be a Form, but I want it to be of the Square class, so I need to cast it. It is compatible since Square inherits from Form.

The only problem is that "formType" is variable, it might indeed be Square, but it could also be "Circle". That is why I need a generic cast for the return object.

If I do a myForm.getClass().getName(), I get "Square". So I need to cast myForm to myForm.getClass().

Do you see the problem ?


Casting doesn't change the object itself. Casting only changes what the compiler allows you to do with the object.

Java provides two ways of describing what you can do with an object: classes and interfaces. The thing you cast to must be something the compiler knows about at compile time. Otherwise, the compiler can't prevent you from doing something silly, like trying to write myCircle.bark().

So you have two choices: if the classes have something in common (an implemented interface, or a class they all derive from) you could try casting to that common description. But it sounds like this is not what you want. Instead, Java forces you to do is to have a chain of if/else statements, which try to cast your object to each concrete class that you might want to do something with, like Square, Circle, etc.

But casting an object to its own class doesn't make sense, because it doesn't give the compiler any information at compile time about what methods the object does or does not have.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜