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.

AndroidJavaClass is the Unity representation of a generic instance of java.lang.Class whereas AndroidJavaObject is the Unity representation of a generic instance of java.lang.Object.

We can create a Java class reference object using AndroidJavaClass and an object of that class using AndroidJavaObject 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 Parcelable. We can put anything extra which is Parcelable into the Bundle or directly into the Intent 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 Uri manually. But since the object first received will be a Parcelable object the question is can we convert it from one object to another by just using AndroidJavaClass and AndroidJavaObject?

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

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.