I'm trying to convert following c# code and behavior to Java but I'm struggling to find the right syntax or programming pattern.
In c# I can use out like in interface IProxy<out Target>
which allows me to implicitly cast IProxy<DerivedElement1>
to IProxy<BaseElement>
but for Java I'm not aware of any similar generic modifiers.
class BaseElement {
public static readonly Property<BaseElement> P1 = new Property<BaseElement>();
}
class DerivedElement1 : BaseElement {
public static readonly Property<DerivedElement1> P2 = new Property<DerivedElement1>();
}
class DerivedElement2 : BaseElement {
public static readonly Property<DerivedElement2> P2 = new Property<DerivedElement2>();
}
class Property<Owner> {
}
interface IProxy<out Target> {
}
class Proxy<Target> : IProxy<Target> {
}
class Program {
public static void doSomething<Target>(IProxy<Target> proxy, Property<Target> property) {
// ...
}
static void Main(string[] args) {
Proxy<DerivedElement1> proxy1 = new Proxy<DerivedElement1>();
doSomething(proxy1, DerivedElement1.P1);
doSomething(proxy1, DerivedElement1.P2);
// expected error
doSomething(proxy1, DerivedElement2.P2);
}
}
It is very important that the expected error appears at compile time and not at run time.
Are you aware of any applicable syntax or pattern that would allow me to implement the same behavior without any additional casting?
I hope you can point me in the right direction, thank you much for your help!
Aucun commentaire:
Enregistrer un commentaire