Typecast Android Object in Untiy

In continuation to previous my previous blogs, where we learnt about how can we use AndroidJavaClass and AndroidJavaObject to achieve simple native Android functionality in Unity, We will move one step ahead and see how can we typecast one Android object to another in Unity.

This post was originally posted at https://agrawalsuneet.github.io/blogs/typecast-android-object-in-unity/ and reposted on Medium on 5th June 2021.

If you have not read the previous blogs, I would strongly recommend to read them first. You can read them on the links below.

is the Unity representation of a generic instance of whereas is the Unity representation of a generic instance of .

We can create a Java class reference object using and an object of that class using but what if we have to typecast one Android object to another of Android class only.

Let’s take an example where we need to get the Parcelable extra from intent in Android and typecast it to Uri object of Android itself.

Android share data between activities using . We can put anything extra which is into the or directly into the and can receive it using getParcelableExtra.

The Java or Kotlin equivalent code for the same will be

//Java Code
Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
//Kotlin Code
val uri = intent.getParcelableExtra<Parcelable>(Intent.EXTRA_STREAM) as Uri
// or
val uri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)

Looking at the Java code it’s easy to understand that Java directly converted it into Uri object but that is not possible in the case of Kotlin as Koltin is not a strongly typed language and the data type of the variable is decided at runtime but not at compile time.

Same in the case of C# also. We have to typecast it to manually. But since the object first received will be a object the question is can we convert it from one object to another by just using and ?

The answer is YES

We can convert one object to another by just using and .

Please continue reading at https://agrawalsuneet.github.io/blogs/typecast-android-object-in-unity/

That’s all for now. You can read my other interesting posts here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.