java 泛型 工厂,泛型的Java工厂模式

I would like my BallUserInterfaceFactory to return an instance of a user interface that has the proper generic type. I am stuck in the example below getting the error:

Bound mismatch: The generic method getBaseballUserInterface(BASEBALL)

of type BallUserInterfaceFactory is not applicable for the arguments

(BALL). The inferred type BALL is not a valid substitute for the

bounded parameter

public class BallUserInterfaceFactory {

public static BallUserInterface getUserInterface(BALL ball) {

if(ball instanceof Baseball){

return getBaseballUserInterface(ball);

}

//Other ball types go here

//Unable to create a UI for ball

return null;

}

private static BaseballUserInterface getBaseballUserInterface(BASEBALL ball){

return new BaseballUserInterface(ball);

}

}

I understand that it cannot guarantee that BALL is a Baseball, and so there is a parameter type mismatch on the getBaseballUserInterface method call.

If I cast the ball parameter in the getBaseballUserInterface method call, then I get the error:

Type mismatch: cannot convert from BaseballUserInterface

to BallUserInterface

Because it can't guarantee that what I am returning is the same type of BALL.

My question is, what is the strategy for dealing with this situation?

(For completeness, here are the other classes required in the example)

public class Ball {

}

public class Baseball extends Ball {

}

public class BallUserInterface {

private BALL ball;

public BallUserInterface(BALL ball){

this.ball = ball;

}

}

public class BaseballUserInterface extends BallUserInterface{

public BaseballUserInterface(BASEBALL ball) {

super(ball);

}

}

解决方案

This is a VERY GOOD question.

You could cast brutely

return (BallUserInterface)getBaseballUserInterface((Baseball)ball);

The answer is theoretically flawed, since we force BASEBALL=Baseball.

It works due to erasure. Actually it depends on erasure.

I hope there is a better answer that is reification safe.

你可能感兴趣的:(java,泛型,工厂)