Ashley
Ashley

Reputation: 53

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.

Upvotes: 3

Views: 411

Answers (2)

Eran
Eran

Reputation: 394136

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.

Upvotes: 5

Darshan Mehta
Darshan Mehta

Reputation: 30849

The instanceof operator allows you determine the type of an object. What we have here is a reference and not an object, if we do A = new MyClass(); then it will created a new Object and that will be referenced by A.

As, there is no object referenced by A, there won't be any object type. However, we can know reference type here, which is MyClass.

Also, instanceof is a null safe operator. Meaning, null instanceof AnyClass will always return false.

Upvotes: 0

Related Questions