Java – invoking methods from generic wildcard references

The following code is simplified to the basic point of the problem:

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);
    }
}

This results in the following compiler error message:

GenericTest. Copyfrom (capture#1-of?) in copyinterface type Method is not applicable to parameter (generictest. Copyinterface) Java / ACAF / SRC / de / tmasoft / acaftest / attributes line 14 Java problem

When I use primitive types as variable targets, I only get a primitive type warning Is there any way to compile without using primitive types?

Solution

You must make your testmethod () generic and declare that the source and target are of the same type:

public <T extends CopyInterface<T>> void testMethod() {
    T target = ...; //initialize the variable
    T source = ...; //initialize the variable
    target.copyFrom(source);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>