1

Consider the following classes

Class A{
    public void m1(){
          System.out.println("test in A.m1()");
    }

    public void m2(){
          //do something a
    }
}


Class B{
    public void m1(){
          //do something b
    }

    public void m2(){
          //do something b
    }
}


Class C{
    public void m1(){
          //do something c
    }

    public void m2(){
          //do something c
    }
}

Class T{
    public void m3(Object obj1){
          obj1.m1();
    }

    public void m4(Object obj1){
          A a=new A();
          m3(a);
    }


}

So now my question is, is there any way I can send an open object to a method which will detect what type of object it is and call method of that object class. In this example I am hoping to see the output: "test in A.m1()"

1
  • This is a task for the Visitor pattern. Commented Dec 22, 2012 at 2:01

1 Answer 1

3

You can use Java's Reflection API to query an arbitrary object to see if it has a method named m1 or m2 and then invoke it. But that is pretty ugly.

Is there anything from stopping you using an interface? Example below (where "..." indicates places where you would put your specific implementation):

interface MyMethods {
  public void m1();
  public void m2();
}

class A implements MyMethods {
  public void m1() { ... }
  public void m2() { ... }
}

class B implements MyMethods {
  ...
}

class C implements MyMethods {
  ...
}

class T {
  public void m3(MyMethods obj1) {
    obj1.m1();
  } 

  public void m4(Object obj1) {
    // Call m3 three times with different object instance types...
    A a = new A();
    m3(a);
    B b = new B();
    m3(b);
    C c = new C();
    m3(c);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

i know how to use interface in this case. but i was wondering if it can be done the way i explained. thanks for your answer though.
What I think you're describing is essentially duck typing, and is a feature of dynamically-typed languages. Java doesn't allow that without a bit of effort to work around things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.