Enforcing Java method return type to fit certain Generic signature

房东的猫 提交于 2019-12-05 21:21:32

The issue you're having with generics is the symptom, not the problem: You're asking your interface to become dependent upon your concrete implementation. If you want your getFoo interface method to return something that is not a WrongFoo, you must return something that is a TrueFoo or a FalseFoo but not a WrongFoo. Your class hierarchy does not have this particular indirection.

To add it, you would need to do something like the following:

class TrueFoo extends SpecialFoo {...}

class FalseFoo extends SpecialFoo {...}

class WrongFoo implements Foo<WrongFoo> {...}

class SpecialFoo implements Foo<SpecialFoo> {  
  SpecialFoo getFoo() {...}
}

Remember that Java supports covariant return types, so by returning SpecialFoo we can implement the contract created in the Foo interface: Foo getFoo() {...}

If you were to need behavior specific to TrueFoo and FalseFoo, you could further parameterize SpecialFoo, and so on, turtles all the way down.

EDIT:

After reading your edit, I don't believe what you're trying to accomplish is supported by the language. It seems like you want to constrain the interface based on the concrete implementation, which would by definition make it not an interface. I think the following example is as close as you're going to get to what you're looking for:

interface CanCopy<T extends CanCopy<T>> {
       T copy();
}

interface FooCanCopy extends CanCopy<Foo> {
}

interface BarCanCopy extends CanCopy<Bar> {
}

class Foo implements FooCanCopy {

    public Foo copy() {
        return null;
    }
}

class Bar implements BarCanCopy {

    public Bar copy() {
        return null;
    }
}

I hope its clear now why the approach doesn't work, even here you still can't prevent someone from doing something like class Baz implements FooCanCopy either. I'd be more curious to know why you're trying to do this? If its to protect developers from making a mistake, there might be other options, i.e. introspecting unit tests or packaging changes.

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