简体   繁体   中英

Will typecasting of null throw an error or exception in java (android)?

Is it advised to use typecasting of null to specific objects and using it in the constructor decreases the quality of code in anyway I'm doing this in the below scenario.

The Actual constructor are like this:

SomeListener(Fragment1 fragment1,String someValue){}

SomeListener(Fragment2 fragment2,String someValue){}

Now when I use this constructor as follows I am getting an error that it is ambiguous and it matches both of above constructors

SomeListener sml = new SomeListener(null,"value");

So what I did was this:

SomeListener sml = new SomeListener((Fragment2)null,"value");

Is this good way of coding or is there a better solution ? Will this solution cause any issue in runtime?

This is described in JLS Sec 4.1 :

The null reference can always be assigned or cast to any reference type.

So no, it won't throw an exception.


An alternative (I won't claim better ) way to do this is to provide static factory methods for the different constructors:

static SomeListener newFragment2Listener(String str) {
  return new SomeListener((Fragment2) null, str);
}

All this does is to hide the casting from users of the class, though. I always find casting a bit ugly; whether that ugliness is a reason for another method is up to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM