Java类型擦除问题 [英] Java Type Erasure Problem
问题描述
我举了一个例子来证明我的问题:
Metrical.java
public interface Metrical< T>
{
double distance(T other);
Widget.java
public class Widget实现Metrical< Widget>
{
private final double value;
public Widget(double value){this.value = value; }
public double getValue(){return value; }
public double distance(Widget other){return Math.abs(getValue() - other.getValue()); }
}
Pair.java
public class Pair< T>
{
private final double value;
private final T object1,object2;
public Pair(T object1,T object2,double value)
{
this.object1 = object1;
this.object2 = object2;
this.value = value;
}
public T getObject1(){return object1; }
public T getObject2(){return object2; }
public double getValue(){return value; }
}
Algorithm.java
import java.util.Set;
public class Algorithm< T extends Metrical< T>>
{
public void compute(Set< T> objects)
{
}
public void compute(Set< Pair< T> ;>对)
{
}
}
因此,在 Algorithm.java 中, Set<对< T >> 被视为 Set T> ,因此我有类型删除问题。然而,有没有什么办法可以避免使用类似这样的命名方法?算法的两种变体都是为了在 T 上运行,但我需要允许不同的参数。他们计算同样的事情,所以为了避免混淆,我宁愿不用不同的名称。有没有什么办法可以解决这个问题?
没有。
你必须记住,有人可以用一个香草套装打电话给你的方法,在这种情况下哪一个会被称为?
这就是为什么你不能做到这一点。就像你不能这样做:
interface A {
void blah(Set set);
void blah(Set< T> set);
}
同样的问题。
类型信息在运行时不可用(即类型擦除)。
I've made an example to demonstrate my problem:
Metrical.java
public interface Metrical<T>
{
double distance(T other);
}
Widget.java
public class Widget implements Metrical<Widget>
{
private final double value;
public Widget(double value) { this.value = value; }
public double getValue() { return value; }
public double distance(Widget other) { return Math.abs(getValue() - other.getValue()); }
}
Pair.java
public class Pair<T>
{
private final double value;
private final T object1, object2;
public Pair(T object1, T object2, double value)
{
this.object1 = object1;
this.object2 = object2;
this.value = value;
}
public T getObject1() { return object1; }
public T getObject2() { return object2; }
public double getValue() { return value; }
}
Algorithm.java
import java.util.Set;
public class Algorithm<T extends Metrical<T>>
{
public void compute(Set<T> objects)
{
}
public void compute(Set<Pair<T>> pairs)
{
}
}
So, in Algorithm.java, Set< Pair< T >> is being seen as a Set< T > and thus I am having type erasure problems. However, is there any way I can get away with something like this without naming the methods differently? Both variants of the algorithm are meant to operate on T's, but I need to allow for different arguments. They compute the same thing, so in an effort to avoid confusion, I would rather not name them differently. Is there any way to accommodate this?
No there isn't.
You have to remember that someone could call your method with just a vanilla Set, in which case which one would be called?
That's why you can't do it. Just like you can't do:
interface A {
void blah(Set set);
void blah(Set<T> set);
}
Same problem.
The type information isn't available at runtime (ie type erasure).
这篇关于Java类型擦除问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!