0

Consider the following (unchangable) API:

interface Bar {} class Foo { public static <T extends Foo & Bar> void doFoo(T param) { System.out.println("I shall be your ruler"); } } 

Now I have written a class that accepts a general Foo but in case that argument is also a Bar, I want to execute doFoo additionally in some method:

class Holder { public Holder(Foo foo) { this.foo = foo; } public void takeOverTheWorld() { if(this.foo instanceof Bar) { // Here I want to execute doFoo(), but I can't hand it over // because the bounds don't match // doFoo(this.foo); ) // Enstablish my reign } } 

Example usage of the Holder:

class Yes extends Foo implements Bar { } // ------ Holder h = new Holder(new Yes()); h.takeOverTheWorld(); // Should print "I shall be your ruler" 

As mentioned in the code comments, I have problems calling doFoo() in the Holder class, because no exact type is known at that time that does extend Foo and implement Bar, so I can't simply cast it to such a type. Is there a way to get around this without changing the interface of Holder, Foo and Bar?

2 Answers 2

2

You can call doFoo in a private helper method which introduces the right type for a cast:

public void takeOverTheWorld() { if(this.foo instanceof Bar) doBarFoo(); } private <T extends Foo & Bar> void doBarFoo() { Foo.doFoo((T)this.foo); } 

You could even do this in takeOverTheWorld if you don't mind that the type is then part of the public interface:

public <T extends Foo & Bar> void takeOverTheWorld() { if(this.foo instanceof Bar) Foo.doFoo((T)this.foo); } 
Sign up to request clarification or add additional context in comments.

1 Comment

I will remember this: Always "infer" the type via a private method if you can't do it normally, haha
0

Make a generic subclass of Holder:

class SubHolder<T extends Foo & Bar> extends Holder { private T fooT; SubHolder(T foo) { super(foo); this.fooT = fooT; } @Override void takeOverTheWorld() { Foo.doFoo(fooT); } } 

1 Comment

This would change the interface of Holder as the class will now be generic only for doing something that nobody does have to know about other than the class. Not a very good solution in the light of encapsulation

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.