Dynamic Casting: - dynamic

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 and 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.

Related

What are the in and out positions in Kotlin Generics?

I want to start with what I know, or at least I think I know, so what I'm asking would be more clear.
First of all, I know that you can declare a variable of a supertype and assign an object of a subtype to take advantage of polymorphism with Inheritence and Interfaces.
I know that generics provide type safety because the type parameters are invariant by definition, so where A is a subtype of B, Foo<A> is not necessarily a subtype of Foo<B>, and may not be used in place depending on mutability of the object. With this, possible exceptions that could arise at runtime due to dynamic dispatching can be caught in compile time.
They also help to define a generic logic for different types: Like in Lists where you have collections of type A objects, but it doesn't change the implementation for type B objects.
Also, I understood why MutableList<String> doesn't count as the subtype of MutableList<Any> because that could result in cases where you create a variable with type MutableList<Any> that holds a reference to a MutableList<String> object, and add an Int element to a List of Strings, which is obviously a problem.
I also understood why List version of the previous example works because Lists are immutable so you can't make any modification to the object that could result in type mismatches.
Lastly, I know that type parameters with in can only be used as function parameters, being consumed, and the ones with out can be used as the function return types, being produced.
Now to the part what I don't understand:
I didn't quite understand what the words consumer and producer actually means in terms of in and out. What does it mean for a type to be in consumed or produced position? Does that mean the object with that type can only be read or write only? Does that have anything to do with the object at all?
What would be the behaviour of the object if, let's say, we don't define it using in or out, or, opposite, we define it using in or out, not talking about the subtype-supertype relationship that I explained above.
I spend the last few days looking at different explanations of this, but I found the lack of examples a big problem, especially because that's how I usually learn.
I can use these concepts in code, but the lack of underlying knowledge or the logic greatly disturbs me, so please, if you decide to take the time to write an explanation, provide it with examples and counter examples of why or how a certain idea works.
Just one correction to your first bullet points: List is not immutable; it is read-only. A List could be an up-cast mutable implementation and some other object that references it could be mutating it.
Producer means the generic type appears as a return type in any functions or properties of the object. You can get T’s out of a List, for instance.
Consumer means the generic type appears as a parameter of any functions or as the type of any var properties of the object. You can put T’s into a MutableList, for example.
Since List produces but doesn’t consume (it doesn’t have any functions with T as a parameter), its type is marked as producing-only, aka covariant, aka out right at the declaration site so its type can always be assumed to be out wherever it’s used even if the out keyword is not used.
Since the List type is always covariant out, any List can be safely upcast to a List where the type is a supertype of the originating type. A List<String> can be cast to List<CharSequence> because any item you get out of it (anything it produces) is going to be a String, and therefore also qualifies as the supertype CharSequence.
The reverse logic would apply for something that is purely a consumer with the type marked in, but it’s harder to come up with a simple example where you would actually have a useful object like this.
A MutableList both produces and consumes, so it is invariant by default, but since it is also a List, a MutableList<String> could be safely cast to a List<CharSequence>. If you have a reference to the List<CharSequence>, you can get CharSequences out of it. The underlying object might continue to have new Strings put into it from the original reference.

how efficient is Object type in vb.net?

I have dynamic item attributes in a dictionary that could hold either a single or a string or 2 other custom classes.
Right now i store the value in a class that has uninitialized variables for all of these and another variable to say which type to get upon request. I don't like it because it's rather clunky and seems to waste memory (since most of the time the value stored is a single).
I figured i could hold any of these in a single object variable type but i don't know what kind of penalties to expect from this, if any. Should i continue with managing the types myself or let vb figure it out?
The main thing you should worry about with the Object type in VB.NET is late-binding. If you call a method on an Object variable (except for those methods that are part of the Object type, such as ToString), the vb runtime has to use reflection to find and call the correct methods on the exact type when they're executed. If you use a specific type for your variable, that lookup will only occur once, when your code is JIT-compiled. I would say that the overhead of late-binding is significant enough that you should avoid it when possible.
However, that doesn't apply to checking the object's type and assigning to a variable with a more specific type. So if you figure out what type of object you have and assign it to the right type of variable before calling methods on it, you should be ok. There is a little bit of overhead to doing that, but it's probably no worse than what you're already doing.
Another reason to avoid late-binding is that it prevents the compiler from doing type checking.

Where is changing the class of an object at runtime allowed

Do you know programming languages where changing the class of an object at runtime is allowed (supported)?
Please give a short example regarding the syntax. Give a use case, if you know any. Examples involving duck typing are welcome as well, so do not shy away from mentioning these languages.
Update: I figured out that Smalltalk has changeClassTo and become. CLOS can do change-class. I found a paper suggesting to use these mechanisms to implement 'husk objects' that are referenced at runtime, but only constructed from some persistence when actually accessed, providing some nifty lazy loading of related objects.
I assume, you mean the following:
You have an object of class A. But you would like to treat it as an object of class B.
There are some constructions possible:
If B is a subclass of A you can cast the object to B (but it should be created as B else you have unexpected (and hopefully unwanted) results).
In some languages you can cast anything to anything. If you know what you are doing, this is great, else prepare for several holes in your foot.
You mention ducktyping. I have no practical experience with it. But As far as I know, duck typing is something like this: "I need an object that support methods X, Y and Z." In that case you don't care about the class. You just want it to quack, swim and walk at your command.
Give a usecase
??? I'd expect you to ask for a solution on a specific use case.
Changing type of an object? I think "No."
But if you like to change part of an objects capabilities or behaviours have a look at loosely coupling!
For example your class holds a member of type File_Saver. There's a public setter accepting any instance of File_Saver and you can inject File_Saver_XML, File_Saver_PDF, ...
It's no common way, but any processing inside a class can be done by 1-n loosely coupled handlers, which you can exchange from outside.
Melt down to your question: You need a wrapper + a setter. :-)
Coming back to the case after some time, I've come to the conclusion that you want duck typing if you feel the need of changing an objects class.

Two possible types for a property

I have a class that is a leaf in the composite pattern. This class has a property that can be either of type A or type B. Their only common interface is of type Object.
How should I support this.
I can
have a add method for each type. That would however mean that I should have two properties of type A and B and should check for null when I want to get the right property.
have one property of type of Object. That would mean I had to check to see which kind of instance it is when I get the property.
What is the best solution for this type of problem? Or any better solutions?
Personally I would choose the single Object property approach. Document what types of objects the property may return, and let the calling code use the available language features to determine the object type, and cast as necessary. Implementing two properties is kinda reinventing the "is-a" operator of your language, and will quickly become unmanageable if you ever need to add more possible types.
Well if you are using a language that supports type abstraction (like Generics in Java or Templates in C++) you can just set that property as a generic type. If not, use Object, Having a method for each type is just an ugly hack (and unmaintanable, if you add more types later).

What do you call a method of an object that changes its class?

Let's say you have a Person object and it has a method on it, promote(), that transforms it into a Captain object. What do you call this type of method/interaction?
It also feels like an inversion of:
myCaptain = new Captain(myPerson);
Edit: Thanks to all the replies. The reason I'm coming across this pattern (in Perl, but relevant anywhere) is purely for convenience. Without knowing any implementation deals, you could say the Captain class "has a" Person (I realize this may not be the best example, but be assured it isn't a subclass).
Implementation I assumed:
// this definition only matches example A
Person.promote() {
return new Captain(this)
}
personable = new Person;
// A. this is what i'm actually coding
myCaptain = personable.promote();
// B. this is what my original post was implying
personable.promote(); // is magically now a captain?
So, literally, it's just a convenience method for the construction of a Captain. I was merely wondering if this pattern has been seen in the wild and if it had a name. And I guess yeah, it doesn't really change the class so much as it returns a different one. But it theoretically could, since I don't really care about the original.
Ken++, I like how you point out a use case. Sometimes it really would be awesome to change something in place, in say, a memory sensitive environment.
A method of an object shouldn't change its class. You should either have a member which returns a new instance:
myCaptain = myPerson->ToCaptain();
Or use a constructor, as in your example:
myCaptain = new Captain(myPerson);
I would call it a conversion, or even a cast, depending on how you use the object. If you have a value object:
Person person;
You can use the constructor method to implicitly cast:
Captain captain = person;
(This is assuming C++.)
A simpler solution might be making rank a property of person. I don't know your data structure or requirements, but if you need to something that is trying to break the basics of a language its likely that there is a better way to do it.
You might want to consider the "State Pattern", also sometimes called the "Objects for States" pattern. It is defined in the book Design Patterns, but you could easily find a lot about it on Google.
A characteristic of the pattern is that "the object will appear to change its class."
Here are some links:
Objects for States
Pattern: State
Everybody seems to be assuming a C++/Java-like object system, possibly because of the syntax used in the question, but it is quite possible to change the class of an instance at runtime in other languages.
Lisp's CLOS allows changing the class of an instance at any time, and it's a well-defined and efficient transformation. (The terminology and structure is slightly different: methods don't "belong" to classes in CLOS.)
I've never heard a name for this specific type of transformation, though. The function which does this is simply called change-class.
Richard Gabriel seems to call it the "change-class protocol", after Kiczales' AMOP, which formalized as "protocols" many of the internals of CLOS for metaprogramming.
People wonder why you'd want to do this; I see two big advantages over simply creating a new instance:
faster: changing class can be as simple as updating a pointer, and updating any slots that differ; if the classes are very similar, this can be done with no new memory allocations
simpler: if a dozen places already have a reference to the old object, creating a new instance won't change what they point to; if you need to update each one yourself, that could add a lot of complexity for what should be a simple operation (2 words, in Lisp)
That's not to say it's always the right answer, but it's nice to have the ability to do this when you want it. "Change an instance's class" and "make a new instance that's similar to that one" are very different operations, and I like being able to say exactly what I mean.
The first interesting part would be to know: why do you want/need an object changes its class at runtime?
There are various options:
You want it to respond differently to some methods for a given state of the application.
You might want it to have new functionality that the original class don't have.
Others...
Statically typed languages such as Java and C# don't allow this to happen, because the type of the object should be know at compile time.
Other programming languages such as Python and Ruby may allow this ( I don't know for sure, but I know they can add methods at runtime )
For the first option, the answer given by Charlie Flowers is correct, using the state patterns would allow a class behave differently but the object will have the same interface.
For the second option, you would need to change the object type anyway and assign it to a new reference with the extra functionality. So you will need to create another distinct object and you'll end up with two different objects.