how to make the parameters of a method generic

I should create a method inside my class that can accept two different types of objects as parameters, then in the method I should check which parameter I received and do the following operations. ex:

public void check(Object obj){
   if(obj istanceOf MyClassOne)
      ...
   else if(obj istanceOf MyClassTwo)
      ...

How should i handle it?

Answer

The solution is not evident.

Consider the following example:

interface I {
    default void print(String method) {
        System.out.println(method + " => " + this.getClass().getCanonicalName());
    }
}

static class A implements I {}
static class A2 extends A {}
static class B implements I {}

static void print(A a) {
    a.print("print(A)");
}

static void print(A2 a2) {
    a2.print("print(A2)");
}

static void print(I i) {
    i.print("print(I)");
}

public static void main(String[] args) {
    print(new A());
    print(new A2());
    print(new B());
}

with output

print(A) => Test.A
print(A2) => Test.A2
print(I) => Test.B

the polymorphic method print admit explicitly A, A2 and I types.

Every type injected to print will use the less generic form of print polymorphism. That is why print(new A2()); use A2 form although any form is valid for this type.

BUT, it is correct only in compile time, at runtime this is not true.

Consider the following example:

A a2_really = (A) new A2();
print(a2_really);

the injected object is A2 but, what method will be used?

print(A) => Test.A2

since it is resolved at compile time, at runtime A form will be used.

Conclusion:

  • if you want to enforce the use of one or other method at compile time, you can write a polymorphic method.
  • if you want to check the instanced method (the object created at runtime), use reflection or encode your logic using other structs (like interfaces).