Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

java - Using parameter that implements multiple interfaces pre-generics

Suppose I have these interfaces:

public interface I1 {
  void foo();
}

public interface I2 {
  void bar();
}

and the classes:

public class A extends AParent implements I1, I2 {
   // code for foo and bar methods here
}

public class B extends BParent implements I1, I2 {
  // code for foo and bar methods here
}

public class C extends CParent implements I1 {
  // code for foo method here
}

Now, with generics I can have a method like:

public <T extends I1 & I2> void method(T param) {
  param.foo();
  param.bar();
}

and I can call it with both A and B as parameters, but not with C (it doesn't implement I2).

Was there a way of achieving this type of type safety pre generics (java < 1.5).

Consider that A, B and C have different inheritance trees, and it's not really an option to do something like AParent and BParent having a common parent themselves.

I know you could do:

public void method(I1 param) {
  param.foo();
  ((I2)param).bar();
}

but then you could also call method(new C()) which doesn't implement I2, so you get into trouble.

So are there any other ways you could have done this?

P.S. : I don't really need to do this, it's mostly out of curiosity that I ask.

question from:https://stackoverflow.com/questions/3108182/using-parameter-that-implements-multiple-interfaces-pre-generics

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Create a third interface I3 extends I1 and I2. Then class A and B both implement I3, and the generic method accepts I3.

That's perhaps the only way to do it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...