1

I'm trying to generify multiple commonly used logic into a single method.

For example, I have two interfaces B and C, which both extend A and have specific properties attached

interface A {}
interface B extends A, PropForB {}
interface C extends A, PropForC {}

interface PropForB {
    PropB prop();
}

interface PropForC {
    PropC prop();
}

I don't want to do any modifications to these classes (I cant just create new method in A, because PropB and PropC are very different). I want to call a method on both of them, so I created methods implementing both cases

private <AClass extends A> List<Result> func(Input input, Class<AClass> clazz) {
    return input.stream()
                .map(clazz::cast)
                .map(this::<AClass>logic)
}

private <T extends B> Result logic(final T x) {}
private <T extends C> Result logic(final T x) {}

In code I want to call like this

func(input, B.class);
func(input, C.class);

But I'm getting an error "Cannot resolve method 'logic'" (and while there is only one method it doesn't bother). How do I properly implement this 'logic' methods in order to make this work?

I do know what "Cannot resolve method 'logic'" is, but I do not understand why generics in Java can't implement specific cases or what I did wrong to do so.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • I only see a declaration of method `logic` (in the code in your question). How are you calling this method? I also don't understand this sentence (also in your question): _while there is only one method it doesn't bother_ – Abra Apr 29 '23 at 12:16
  • @Abra `logic` is called inside `func` - which shares some code between `B` and `C`. By `it doesn't bother` I mean compiler not giving me an error, while there is only one `logic` implemented, for example, for B. – Silverlight777 Apr 29 '23 at 13:08

0 Answers0