简体   繁体   English

未经检查的泛型抽象继承(java)

[英]Unchecked generic in abstract inheritance (java)

I'm getting a compilation warning: "ExampleConsumer.java uses unchecked or unsafe operations." 我收到编译警告:“ ExampleConsumer.java使用未经检查或不安全的操作。” on line return example.distance(other); 在线return example.distance(other); . How do I properly check the type? 如何正确检查类型? Obviously I need to enforce that the types are the same. 显然,我需要强制类型相同。

Here's my code: 这是我的代码:

Example.java Example.java

public abstract class Example<T, U> {
  public T t;
  public U u;

  public Example(T t, U u) {
    this.t = t;
    this.u = u;
  }

  abstract double distance(Example<T, U> other);
}

SpecialExample.java SpecialExample.java

public class SpecialExample extends Example<Integer, Double> {
  public SpecialExample(Integer i, Double d) {
    super(i, d);
  }

  @Override
  double distance(Example<Integer, Double> other) {
    return (double)(t - other.t) + u * other.u;
  }
}

BadExample.java BadExample.java

public class BadExample extends Example<String, String> {
  public BadExample(String s1, String s2) {
    super(s1, s2);
  }

  @Override
  double distance(Example<String, String> other) {
    return (double)(t.length() + other.t.length()) + (u.length() * other.u.length());
  }
}

ExampleConsumer.java ExampleConsumer.java

public class ExampleConsumer<E extends Example> {
  private E example;

  public ExampleConsumer(E example) {
    this.example = example;
  }

  public double combine(E other) {
    return example.distance(other);
  }
}

Main.java Main.java

class Main {
  public static void main(String[] args) {
    SpecialExample special = new SpecialExample(1, 2.0);

    ExampleConsumer<SpecialExample> consumer = new ExampleConsumer<>(special);

    BadExample bad = new BadExample("foo", "bar");

    consumer.combine(special); // compiles with warning
   // consumer.combine(bad); // doesn't compile = good!
  }
}

Here's one solution: 这是一种解决方案:

ExampleConsumer.java ExampleConsumer.java

public class ExampleConsumer<A, B, E extends Example<A, B>> {
  private E example;

  public ExampleConsumer(E example) {
    this.example = example;
  }

  public double combine(E other) {
    return example.distance(other);
  }
}

Main.java Main.java

class Main {
  public static void main(String[] args) {
    // ...
    ExampleConsumer<Integer, Double, SpecialExample> consumer = new ExampleConsumer<>(special);
    // ...
  }
}

But I'd rather not have to repeat the Double/Integer types in Main.java :/ 但是我宁愿不必在Main.java中重复Double / Integer类型:/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM