eleniVl
eleniVl

Reputation: 33

Java Generics - Implement method with two generic types using types with the same class name

I'm facing the following issue. Due to versioning reasons i need to convert an object into another using the same class name but different package. Im using an interface and an implementation class as the following ones

//interface class
     public interface SampleConverter {
          <T,S> T convert(S type);
    }



//concrete class
import com.test.v1.A
public class TestConverter implements SampleConverter {
    <A,com.test.v2.A> A convert(com.test.v2.A type) { // compile time error
        ....
   }
}

but im getting compilation error when i use the fully qualified name of the class inside diamond operator. What is the problem when using the full package of the class like this and what could be a possible solution? Thanks in advance!

Upvotes: 0

Views: 719

Answers (1)

Rolf Sch&#228;uble
Rolf Sch&#228;uble

Reputation: 690

Let's have a look at your TestConverter class. The line

<A,com.test.v2.A> A convert(com.test.v2.A type) { ....

defines a new generic methods. In such declarations, the identifiers between < and > are placeholders for types, not actual types. And type identifiers may not contains dots in their names. A correct way to declare the method would be:

<A, B> A convert(B type) { ... }

exactly like you did it in the interface.

I think what you really wanted is this:

public interface SampleConverter<T, S> {
      T convert(S type);
}

import com.test.v1.A
public class TestConverter implements SampleConverter<A, com.test.v2.A> {
    public A convert(com.test.v2.A type) {
        ....
   }
}

Upvotes: 1

Related Questions