Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect type of an uninitialized object

Suppose I have an uninitialized object such as:

MyClass A=null;

How do I detect that the type of A is MyClass? A instanceof MyClass.class is not working. It's returning false. And A.getClass() throws a NullPointerException. Is there a way to find the type of such uninitialized objects?

Edit:

The actual scenario is that MyClassA, MyClassB and MyClassC are subclasses of MyClass. So I'd be using the following code:

MyClassB B=null;
MyClass MC=B;

Now, at runtime, I need to determine if MC is an "instance of" MyClassA or MyClassB or MyClassC. Is there a way to do that?

Edit 2:

By detecting the type at runtime, I'd be able to do something like:

MyClass C=null;
...
//detect the type of C and instantiate the base class with an instance of that type
MyClass MC=new MyClassC();

Basically, I'll be passed the objects of all the subclasses, and I'll have to determine the type of each object and instantiate the base class with that type and return it.

Edit 3:

Finally found a partial way to do it! Relying on polymorphism to do that:

MyClassC C=null;
detect(C);
....
detect(MyClassA a){}
detect(MyClassB b){}
detect(MyClassC c){ //MyClassC detected! }

However, if I'm passed the MyClass object,this wouldn't work.

like image 292
Ashley Avatar asked Jan 18 '26 20:01

Ashley


1 Answers

You know the static (compile time) type of that variable - it's MyClass. You don't need instanceof or A.getClass.

instanceof or A.getClass are useful when you need to know the run-time time of the instance referred by the variable. This has no meaning when the variable contains null.

EDIT :

If MC is null, it's not an instance of anything. It makes no difference if you write

MyClassB B=null;
MyClass MC=B;

or

MyClassC C=null;
MyClass MC=C;

or

MyClass MC=null;

In all those cases MC would contain the same null value, and it won't have any type other than its compile-time type, which is MyClass.

EDIT 2:

You can instantiate the correct class when you assign to MC :

MyClassC C = null;
MyClass MC = C==null?new MyClassC():C;

At the time you assign C to MC, you know the type of C and you can create an instance of MyClassC if it's null.

like image 99
Eran Avatar answered Jan 20 '26 08:01

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!