简体   繁体   中英

Java generic method, how to make two parameters to have the same type?

I have the following interface and classes:

public interface SomeInterface {
    ...
}

public class TypeA implements SomeInterface {
    ...
}

public class TypeB implements SomeInterface {
    ...
}

And I have the following method in some other class:

public static <T extends SomeInterface> void foo(T a, T b) {
    ...
}

Now, how do I make sure both a and b are from the same class? (either both TypeA or both TypeB , and I want to get compilation error when the first one is TypeA but the second one is TypeB )


One solution I found is to add a type to the interface, like this:

public interface SomeInterface<T> {
    ...
}

public class TypeA implements SomeInterface<TypeA> {
    ...
}

public class TypeB implements SomeInterface<TypeB> {
    ...
}

And also modify the method like this:

public static <T> void foo(SomeInterface<T> a, SomeInterface<T> b) {
    ...
}

This solutions works but it seems a bit weird to me because I have to write the class name twice: class A implements SomeInterface<A> . I'm wondering if there are any better solutions than the one above. Thank you.

In this case I would use if these are the only two interfaces:

public static <T extends SomeInterface> void foo(TypeA a, TypeA b) {
public static <T extends SomeInterface> void foo(TypeB a, TypeB b) {

but your solution will also work when there are unknown number of interfaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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