java – 从通用通配符引用调用方法

以下代码简化为问题的基本要点:

public class GenericTest 
{
    private interface copyInterface<T extends copyInterface<T>>
    {
        public void copyFrom(T source);
    }

    public void testMethod()
    {
        copyInterface<?> target;
        copyInterface<?> source;
        target.copyFrom(source);
    }
}

这会导致以下编译器错误消息:

GenericTest.copyInterface类型中的copyFrom(capture#1-of?)方法不适用于参数(GenericTest.copyInterface)GenericTest.java / ACAF / src / de / tmasoft / acaftest / attributes第14行Java问题

当我使用原始类型作为变量目标时,我只得到一个原始类型的警告.有没有办法在不使用原始类型的情况下编译?

解决方法

你必须使你的testMethod()通用,并声明源和目标是相同的类型:

public <T extends copyInterface<T>> void testMethod() {
    T target = ...; //initialize the variable
    T source = ...; //initialize the variable
    target.copyFrom(source);
}

相关文章

Java中的String是不可变对象 在面向对象及函数编程语言中,不...
String, StringBuffer 和 StringBuilder 可变性 String不可变...
序列化:把对象转换为字节序列的过程称为对象的序列化. 反序...
先说结论,是对象!可以继续往下看 数组是不是对象 什么是对...
为什么浮点数 float 或 double 运算的时候会有精度丢失的风险...
面试题引入 这里引申出一个经典问题,看下面代码 Integer a ...