Using an object in a method by passing it as a parameter

Larry Ko :

I'm facing a situation that involves class and methods.

To make it simple, imagine you have 2 classes: A and B

In the class A, I have a method called, lets say, "jumpOnOtherClass". In the class B, I have another method called "doThings".

I'd like the class A method to take as argument any object of any class, so that it first checks if the object is null (so it can creates a new instance of the object passed), and then execute a method of the object's class.

Here is an example code:

class MyMainClass
{
  private A objectA = new A();
  private B objectB;

  public void main()
  {
    this.objectA.jumpOnOtherClass(this.objectB,"doThings");
  }
}

class A
{
  public void jumpOnOtherClass(Object objectFromAnyClass, String methodToInvoke)
  {
    if(objectFromAnyClass == null) objectFromAnyClass = new DefaultConstructorOfB();

    objectFromAnyClass.getMethod(methodToInvoke);
  }
}

class B
{
  public void doThings()
  {
    //Do some stuff here
  }
}

I know there are exception to take in consideration but for the example we'll assume that the class, and the methods exist and are found :)

I tried things with "java.lang.reflect" but it seems not to be the good way to achieve what I try to do...

Any help would be really nice!

Thanks and have a nice day!

Halex :

The only problem is that if the reference is null, you cannot really know the class of the "object" at runtime, so you will need to fix this by providing additional information.

I suggest this approach (it does involve reflection):

public <T> void jumpOnOtherClass(T objectFromAnyClass, Class<T> classType, String methodToInvoke)
            throws
            NoSuchMethodException,
            IllegalAccessException,
            InvocationTargetException,
            InstantiationException
    {
        if(objectFromAnyClass == null) 
            objectFromAnyClass = classType.getDeclaredConstructor().newInstance();

        classType.getMethod(methodToInvoke).invoke(objectFromAnyClass);
    }

and use it like this:

jumpOnOtherClass(this.objectB, B.class, "doThings");

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=393700&siteId=1