Java dynamic class cast
I'm aware that this could be a possible duplicate, but the other threads haven't solved my problem completely.
Let's say I have the following classes A and B which extend BasicClass.
public abstract class BasicClass {
// ...
}
public class A extends BasicClass {
// ...
}
public class B extends BasicClass {
// ...
}
And now I want to cast class A to B dynamically.
a.getClass().cast(bClass.newInstance);
but every time I get an Exception.
java.lang.ClassCastException
at java.lang.Class.cast(Unknown Source)
Can you tell me why?
Copyright License: Author:「user2948795」,Reproduced under the CC 4.0 BY-SA copyright license with link to original source & disclaimer. Link to:https://stackoverflow.com/questions/27008532/java-dynamic-class-cast
About “Java dynamic class cast” questions
I'm looking for a simple solution to pass values of attributes/objects between two java programs. The programs are identical (running on separated nodes) and can't set/get variables though call of ...
|
I'm aware that this could be a possible duplicate, but the other threads haven't solved my problem completely.
Let's say I have the following classes A and B which extend BasicClass.
public abstr...
|
I have two classes, base class and a derived class.
The base class has a virtual method.
Here is my test example:
class Base
{
public:
virtual void Hello() { cout << "-> Hello Base"...
|
I want to cast this:
class Base
{
public:
virtual ~Base(){};
};
class Der : public Base {};
int main()
{
const Base* base = new Der;
Der* der = dynamic_cast<Der*>(base); // Err..
|
I thought the first "pd" can cast to Base class.
I tried to change Derived *pd; to Base *pd; and pd = dynamic_cast<Derived*>(pba); to pd = dynamic_cast<Base*>(pba);
However, these two...
|
Having being taught during my C++ days about evils of the C-style cast operator I was pleased at first to find that in Java 5 java.lang.Class had acquired a cast method.
I thought that finally we ...
|
Here the second cast gives an error saying
cast.cc:35:35: error: cannot dynamic_cast ‘base’ (of type ‘class CBase*’) to type ‘class CDerived*’ (source type is not polymorphic)
CBase * base =
|
As I understand it, what makes dynamic cast different from a static cast is its use of RTTI, and the fact that it fails if the dynamic type of a variable- when casting from base to derived- does no...
|
In Primer c++ 5th
class A {
public:
A() : a(1) {}
virtual ~A() = default;
private:
int a;
};
class B : public A {
public:
B() : b(2) {}
private:
|
I am new to C++ and came to a point, where I generate an overhead with classes. I have a QTcpSocket and read messages from it and create objects, for example MessageJoin, MessagePart, MessageUserDa...
|
|
|