2 object arguments must be from the same class

I want to create a method in which 2 or more object parameters must be passed, which must be from the same class.
The object foo and bar must be members of the same class.

public void method(Object foo, Object bar) {
}

I remember that I had seen something like this before, but I can’t remember how it was done exactly.

public void method(Object<?> foo, Object<?> bar) {
}
+4
source share
4 answers

I think you mean something like this:

public <T> void method(T foo, T bar) {
}

Here you define a generic type Twithout any restrictions and require that both parameters have a type T(or subclass). Then you can call it like this:

method("string1", "string2"); //ok
method(Integer.valueOf(1), Long.valueOf(1) ); //works, Compiler will infer T = Number
this.<Integer>method(Integer.valueOf(1), Long.valueOf(1) ); //You set T = Integer, so the compiler will complain
+3
source

You can do this by checking the class of the object to see if they are the same

public void method(Object foo, Object bar) {
    if(!foo.getClass().equals(bar.getClass())) {
        throw new IllegalArgumentException("Exception");
    }
}

, java Object .

:

public <T> void method(T foo, T bar, Class<T> clazz) {
}

:

method("string 1", "string 2", String.class);
+2

to try

public <T,U extends T> void method(T foo, U bar) { 
}
+2
source

An alternative solution with Java 8 would be to use a template as follows:

public <T> Consumer<T> method(T foo) {
    return bar -> {
        // do stuff;
    };
}

@Test
public void test() {
    method(Integer.valueOf(1)).accept(Long.valueOf(2)); // No good
    method(Integer.valueOf(1)).accept(Integer.valueOf(1)); // ok
    method((Number) Integer.valueOf(1)).accept(Long.valueOf(2)); // ok
}
0
source

All Articles