Xamarin Android Binding to Java Type which inherits Generic Type

為{幸葍}努か 提交于 2019-12-25 06:28:46

问题


I'm looking for a workaround for the following problem. Given a class hierarchy in Java:

public interface Bar<T> { 
    getValue<T>();
}

public abstract class BarImpl<T> implements Bar<T> {

}

public class Foo extends BarImpl<Double> {
    @override 
    public Double getValue() {
        // .. 
    }
}

Xamarin.Android generates wrappers as follows:

// Now in C# land
public interface Bar 
{
    // Xamarin.Android omits T Value { get; }
}

public partial abstract class BarImpl : Bar  
{
    // Xamarin.Android omits abstract T Value { get; }
}

public partial class Foo : BarImpl
{
    // COMPILE ERROR HERE. No method to override
    public override java.lang.Double Value 
    {
        get { /* ... */ }
    }
}

Now I'm well aware that Java compilation strips out generics information, so this isn't actually an easy problem to solve but I do want to know if:

  • Anyone has come across similar problems in java.android

  • What clever solutions you employed to bind this class hierarchy?

I'm only interested in the getter of Value on Foo (bound c# class) and some way to access it via the base interface (cast is OK).


回答1:


The generator generates partial classes. Extending these could be a solution. All you have to do, is to add files to the Additions folder and ad your stuff to the partial classes. My idea would look like:

// custom interface
public interface IMyBar<T> : Bar<T>
{
    public T Value { get; }
}

// extend the partial base class
public partial abstract class BarImpl : IMyBar<Java.Lang.Double>  
{
    public abstract Java.Lang.Double Value { get; }
}

// compiler generates the rest
public partial class Foo
{
    // COMPILE ERROR HERE. No method to override
    public override Java.Lang.Double Value 
    {
        get { /* ... */ }
    }
}



回答2:


I ended up going another route and creating my own java wrappers around these generic interfaces so things would bind without issues. So instead of using the supplied interfaces which inherited from generics, I created my own which did not inherit and passed them into java methods which wrapped the previous ones.



来源:https://stackoverflow.com/questions/36533263/xamarin-android-binding-to-java-type-which-inherits-generic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!