How to cast object to object
How to cast object to object
Can we cast a generic object to a custom object type in javascript?
For example, I already have this object somewhere in the code, it is a generic object:
I have the constructor for a Person object:
Is there a simple syntax that allows us to convert person1 to an object of type Person?
7 Answers 7
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The answer of @PeterOlson may be worked back in the day but it looks like Object.create is changed. I would go for the copy-constructor way like @user166390 said in the comments.
The reason I necromanced this post is because I needed such implementation.
Nowadays we can use Object.assign (credits to @SayanPal solution) & ES6 syntax:
ES5 answer below
Using a shorter version, 1.5 liner:
jsfiddle
No.
Though this obviously won’t work for privileged methods created inside of the Person constructor—like your getFullName method.
This is not exactly an answer, rather sharing my findings, and hopefully getting some critical argument for/against it, as specifically I am not aware how efficient it is.
Here is link to my JSFiddle, and also the main part of the code:
How to cast Object to its actual type?
How can I cast obj to what its actual type is?
11 Answers 11
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
If you know the actual type, then just:
If you don’t know the actual type, then: not really, no. You would have to instead use one of:
I don’t think you can (not without reflection), you should provide a type to your function as well:
UPD:
This may work for you:
If your MyFunction() method is defined only in one class (and its descendants), try
If you have a large number in unrelated classes defining the function you want to call, you should define an interface and make your classes define that interface:
In my case AutoMapper works well.
AutoMapper can map to/from dynamic objects without any explicit configuration:
Similarly you can map straight from dictionaries to objects, AutoMapper will line up the keys with property names.
Cast it to its real type if you now the type for example it is oriented from class named abc. You can call your function in this way :
if you don’t know the function it can be done in a different way. Not easy always. But you can find it in some way by it’s signature. If this is your case, you should let us know.
If multiple types are possible, the method itself does not know the type to cast, but the caller does, you might use something like this:
Restrictions on the type could be added using the where keyword after the parentheses.
Casting objects in Java
I’m confused about what it means to cast objects in Java.
What is happening here? Does the variable type change, or is it the object within the variable that changes? Very confused.
10 Answers 10
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Have a look at this sample:
Say you have a superclass Fruit and the subclass Banana and you have a method addBananaToBasket()
The method will not accept grapes for example so you want to make sure that you’re adding a banana to the basket.
Fruit myFruit = new Banana();
((Banana)myFruit).addBananaToBasket(); ⇐ This is called casting
The example you are referring to is called Upcasting in java.
It creates a subclass object with a super class variable pointing to it.
The variable does not change, it is still the variable of the super class but it is pointing to the object of subclass.
For example lets say you have two classes Machine and Camera ; Camera is a subclass of Machine
If you execute the above statements it will create an instance of Camera class with a reference of Machine class pointing to it.So, now the output will be «Camera Started» The variable is still a reference of Machine class. If you attempt machine1.snap(); the code will not compile
The takeaway here is all Cameras are Machines since Camera is a subclass of Machine but all Machines are not Cameras. So you can create an object of subclass and point it to a super class refrence but you cannot ask the super class reference to do all the functions of a subclass object( In our example machine1.snap() wont compile). The superclass reference has access to only the functions known to the superclass (In our example machine1.start() ). You can not ask a machine reference to take a snap. 🙂
Casting and type conversions (C# Programming Guide)
Implicit conversions: No special syntax is required because the conversion always succeeds and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.
Explicit conversions (casts): Explicit conversions require a cast expression. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons. Typical examples include numeric conversion to a type that has less precision or a smaller range, and conversion of a base-class instance to a derived class.
User-defined conversions: User-defined conversions are performed by special methods that you can define to enable explicit and implicit conversions between custom types that do not have a base class–derived class relationship. For more information, see User-defined conversion operators.
Conversions with helper classes: To convert between non-compatible types, such as integers and System.DateTime objects, or hexadecimal strings and byte arrays, you can use the System.BitConverter class, the System.Convert class, and the Parse methods of the built-in numeric types, such as Int32.Parse. For more information, see How to convert a byte array to an int, How to convert a string to a number, and How to convert between hexadecimal strings and numeric types.
Implicit conversions
For a complete list of all implicit numeric conversions, see the Implicit numeric conversions section of the Built-in numeric conversions article.
For reference types, an implicit conversion always exists from a class to any one of its direct or indirect base classes or interfaces. No special syntax is necessary because a derived class always contains all the members of a base class.
Explicit conversions
However, if a conversion cannot be made without a risk of losing information, the compiler requires that you perform an explicit conversion, which is called a cast. A cast is a way of explicitly informing the compiler that you intend to make the conversion and that you are aware that data loss might occur, or the cast may fail at run time. To perform a cast, specify the type that you are casting to in parentheses in front of the value or variable to be converted. The following program casts a double to an int. The program will not compile without the cast.
For a complete list of supported explicit numeric conversions, see the Explicit numeric conversions section of the Built-in numeric conversions article.
For reference types, an explicit cast is required if you need to convert from a base type to a derived type:
A cast operation between reference types does not change the run-time type of the underlying object; it only changes the type of the value that is being used as a reference to that object. For more information, see Polymorphism.
Type conversion exceptions at run time
In some reference type conversions, the compiler cannot determine whether a cast will be valid. It is possible for a cast operation that compiles correctly to fail at run time. As shown in the following example, a type cast that fails at run time will cause an InvalidCastException to be thrown.
The Test method has an Animal parameter, thus explicitly casting the argument a to a Reptile makes a dangerous assumption. It is safer to not make assumptions, but rather check the type. C# provides the is operator to enable you to test for compatibility before actually performing a cast. For more information, see How to safely cast using pattern matching and the as and is operators.
C# language specification
For more information, see the Conversions section of the C# language specification.
How to cast System.Object[*] to System.Object[] II
I have got a similar problem like Cheva had in his Question:
I use an external library (Reuters EIKON API) via the COM interop functionality.
After submitting a request, the object gets updated and its data member gets updated. The Object catalogue shows this for the Data member:
In the debug mode, I can see, that after submitting the request, DataStatus changes to dataset_full and the Data member is actually filled.
The data member is shown as
My problem is that I can’t access this object. I can cast it to object[] or string[] or anything. I can’t even find out the type of it.
It always says System.Object[*] can not be cast to System.Object[]
Has anyone seen a similar error?
1 Answer 1
Then you can foreach through it.
Or you can access individual entries by index, like this:
You can cast to string in the usual ways, (string)first if you expect it to be a string every time, or something like first as string (then check for null) if you want to support other objects.
If instead you want to copy the «weird» array to a 0-indexed array, see the linked thread without the numeral II in the title. Indexes will change, of course. For example object[] newArray = new object[dataAsArray.Length]; dataAsArray.CopyTo(newArray, 0);
Much later edit:
In either case an InvalidCastException is thrown:
Unable to cast object of type ‘System.Object[*]’ to type ‘System.Object[]’.
This is a bug, I would say. The members exist, and I did not ask to cast to that type, I asked for late-binding to members that exist.
You can work around this bug in the following way:
Casting to object with late binding (i.e. from dynamic ) does not appear to be affected by the bug. The the next cast, from object to Array (or to IList ), is a normal down-cast with no dynamic magic, and that works of course.
With this, my answer has become useful (years later).
I am just realizing that an answer by RoadBump in a linked thread also gives this information, so go up-vote that answer.
Источники информации:
- http://stackoverflow.com/questions/12234097/how-to-cast-object-to-its-actual-type
- http://stackoverflow.com/questions/5306835/casting-objects-in-java
- http://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions
- http://stackoverflow.com/questions/23366984/how-to-cast-system-object-to-system-object-ii