如何使用与参数相同的类的泛型创建构造函数

时间:2013-09-16 13:32:16

标签: java generics

我有一个表达式:

public class Expression < E extends Number, V extends Number >
{
   public Expression(E lV, OPERATION operation, V rV) {
   }

   public Expression(Expression< E, V > lE, OPERATION operation, Expression< E, V > rE) {
   }
}

Expression.java编译没有错误。

这是我的主要类代码。

public static void main(String[] args)
{
        // Line 1. 
    refactored.Expression< ?, ? > ex1 = new refactored.Expression< Double, Float >(10d, OPERATION.PLUS, 10f);

        // Line 2.
    refactored.Expression< ?, ? > ex2 = new refactored.Expression< Double, Float >(-3d, OPERATION.MUL, 1f);

        // Line 3.
    refactored.Expression< ?, ? > ex3 = new refactored.Expression< refactored.Expression< Double, Float >, refactored.Expression< Double, Float > >(ex1, OPERATION.MINUS, ex2);
}

第3行没有编译,它说:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
The constructor Expression<Expression<Double,Float>,Expression<Double,Float>>(Expression<capture#1-of ?,capture#2-of ?>, OPERATION, Expression<capture#3-of ?,capture#4-of ?>) is undefined
Bound mismatch: The type Expression<Double,Float> is not a valid substitute for the bounded parameter <E extends Number> of the type Expression<E,V>
Bound mismatch: The type Expression<Double,Float> is not a valid substitute for the bounded parameter <V extends Number> of the type Expression<E,V>

它出了什么问题?

3 个答案:

答案 0 :(得分:3)

表达式不会扩展数字,因此它不是合法的类型参数。

编辑 - 发表评论
我不确定为什么你需要这个通用解决方案...
你可以拥有像

这样的东西
interface Expression {
  Number compute();
}

class AtomicExpression implements Expression {
  private final Number number;
  AtomicExpression(Number number) {
    this.number = number;
  }
  public Number compute() {
    return number;
  }
}

class BinaryExpression implements Expression {
  private final Expression expr1;
  private final Expression expr2;
  private final Operator op;
  AtomicExpression(Expression expr1, Expression expr1. Operator op) {
    this.expr1 = expr1;
    this.expr2 = expr2;
    this.op = op;
  }
  public Number compute() {
    return op(expr1.compute(), expr2.compute());
  }
}

答案 1 :(得分:0)

refactored.Expression&LT; ?,? &GT; ex3 = new refactored.Expression&lt; Double,Float&gt;(ex1,OPERATION.MINUS,ex2);

这应该有用。

答案 2 :(得分:0)

从你得到的错误中可以明显看出Expression<?, ?>不是Number的子类。如果你真的想在构造函数中接受Expression,那么你需要从泛型中删除上部绑定参数(Number)。

这样的事情对你有用:

public class Expression <E, V> {
    public Expression(E lV, OPERATION operation, V rV) {}
    public Expression(Expression< E, V > lE, OPERATION operation, Expression< E, V > rE) {}
}

更新:这应该适用:

Expression< Double, Float > ex1 = new Expression< Double, Float >(10d, OPERATION.PLUS, 10f);

Expression< Double, Float > ex2 = new Expression< Double, Float >(-3d, OPERATION.MUL, 1f);

Expression< ?, ? > ex3 = new Expression
 < Expression< Double, Float >, Expression< Double, Float > >(ex1, OPERATION.MINUS, ex2);