Home > OS >  How to get the .NET Type from Java.Lang.Class instance?
How to get the .NET Type from Java.Lang.Class instance?

Time:10-20

I'm using Xamarin.Android and I'm trying to extend the functionality of the default FragmentFactory.

public class ExtendedFragmentFactory : FragmentFactory
{
    public override Fragment Instantiate(ClassLoader classLoader, string className)
    {
        Class javaClass = Class.ForName(className, false, classLoader);
        var instance = javaClass.NewInstance();
    }
}

If I create a new instance using NewInstance(), then I am able to call GetType() on instance which does give me the .NET Type but how would I do this without unnecessarily creating an instance?

I'm trying to get the Dependency Container to create the Fragment so I am not able to use the default instantiation method that Android uses with FragmentManager or FragmentFactory. My Fragment classes will have dependencies injected into them via their constructor, in other words, I will not have a parameterless constructor which the default instantiation implementation expects.

Is there any way to get the .NET Type from Java.Lang.Class or the specified parameters in the Instantiate method?

Is there any way I can use the className parameter to work out what the .NET Type is?

CodePudding user response:

Well, Java.Lang.Class by default has the GetType() method

Class javaClass = Class.ForName(className, false, classLoader);
var dotNetType = javaClass.GetType();

Good luck!

CodePudding user response:

By using the RegisterAttribute, I was able to find a way to ensure className has the fully qualified name of the .NET Type.

[Register("Namespace.SomeFragment")
public class SomeFragment : Fragment
{
}

This is a somewhat tedious process especially if you have many Fragment classes (like me).

If there is a way to use the default value of className and somehow work out of the .NET Type from it, that would be much better, but this will suffice for now.

  • Related