0

I want to write a method which would receive different type of objects dynamically. Once I receive the dynamic object, I have logic inside method to do something based on the properties associated with that object. It would be something like below:

MainClass{
class1 obj1;//all these are pojo
class2 obj2;
class3 obj3;
method1(<dynamic_object>)
}
    method1(<dynamic_object>){
        if(dynamic_object.property 1 == true){
            callmethod2(dynamic_object.property 1)
        }
        else{
            callmethod3(dynamic_object.property 1)
        }
    }

Here dynamic_objects are of different type. How can I achieve this in Java? I do not want to use reflection here.

3
  • 1
    Use a common interface or just Object along with instanceof and casts or reflection. I guess Apache Commons BeanUtils would help you. Commented Apr 1, 2016 at 16:33
  • 1
    Learn about polymorphism. Commented Apr 1, 2016 at 16:36
  • You need 'Polymorphism' here, which you can achieve in Java using an Interface, Abstract class or subclasses implementing a common superclass. Commented Apr 1, 2016 at 16:44

5 Answers 5

2

In order to recognize the type of the object you can use the instanceof operator.

 private void instanceOfMethodExample(Object object){
    if(object instanceof String)
        print("Its a String!");
    else if(object instanceof Integer)
        print("Its an Int!");
    else
        print("Its a " + object.getClass().getName()); // by calling getClass().getName() method you take the class name of the object as a String
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use the visitor pattern, In a nutshell you can have something like this:

public class Visitor {

    interface UserVisitor {
        public void visit(CarUser user1);

        public void visit(BusUser user2);
    }


    static class VehicleVisitor implements UserVisitor {

        private Car vehicle;
        private Bus bus;

        VehicleVisitor(Car vehicle, Bus bus) {
            this.vehicle = vehicle;
            this.bus = bus;
        }

        public void visit(CarUser user1) {
            user1.setCar(vehicle);
        }

        public void visit(BusUser user2) {
            user2.setBus(bus);
        }
    }

    interface UserVisitorClient {
        void accept(UserVisitor visitor);
    }

    static class CarUser implements UserVisitorClient {

        private Car car;

        public void accept(UserVisitor visitor) {
            visitor.visit(this);
        }

        public void setCar(Car car) {
            this.car = car;
        }

        public Car getCar() {
            return car;
        }
    }

    static class BusUser implements UserVisitorClient {

        private Bus bus;

        public void accept(UserVisitor visitor) {
            visitor.visit(this);
        }

        public void setBus(Bus bus) {
            this.bus = bus;
        }

        public Bus getBus() {
            return bus;
        }
    }

    static class Car {

        @Override
        public String toString() {
            return "CAR";
        }
    }
    static class Bus {

        @Override
        public String toString() {
            return "BUS";
        }
    }

    public static void main(String[] args) {
        List<UserVisitorClient> users = new ArrayList<UserVisitorClient>();
        CarUser user1 = new CarUser();
        users.add(user1);
        BusUser user2 = new BusUser();
        users.add(user2);

        for (UserVisitorClient user : users) {
            VehicleVisitor visitor = new VehicleVisitor(new Car(), new Bus());
            user.accept(visitor);
        }

        System.out.println(user1.getCar());
        System.out.println(user2.getBus());
    }
}

Which is just an example. But it shows that basically you can use this pattern to support what you're trying to accomplish.

In your code, you could have:

void method1(VisitorClient client) {
    client.accept(someVisitor);
}

This will allow you to reach o more object oriented solution, relying in polymorphism instead of reflection or instanceof.

Comments

0

The best option is to use a common interface

interface HasProperty {
   boolean isSet();
}

void method1(HasProperty object) {
     if (object.isSet())
        method2(object);
     else
        method3(object);
}

Or even better have a method to call to perform an action.

interface MethodOne {
   void method1();
}

MethodOne object = ...
object.method1(); // calls the appropriate method for this object.

Comments

0

Use superclass of all objects- "Object" and check the type of object using instanceof operator.

method1(Object obj){
if(obj instanceof dynamic_object){
    callmethod2(dynamic_object.property 1)
}
else if(obj instanceof dynamic_object2) {
    callmethod3(dynamic_object2.property 1)
}

}

Comments

-1

EDIT: Given your newly posted code, you may even simply wish to use an common interface, or base class, for the dynamic objects.

Interface:

public interface CommonInterface {
    boolean isValid();
    void method1();
    void method2();
    void method3();
}

Class Example:

public Class1 implements CommonInterface {
    public boolean isValid() {
        return true;
    }

    public void method1() {
        System.out.println("Method 1");
    }

    public void method2() {
        System.out.println("Method 2");
    }

    public void method3() {
        System.out.println("Method 2");
    }
}

Code:

public void doSomethingWithCommonObjects(CommonInterface object) {
    object.method1();
    if (object.isValid()) {
        object.method2();
    } else {
        object.method3();
    }
}

Each of the dynamic objects simply need to implement the CommonInterface interface, which would enforce method1(), method2(), method3() and property1() signatures for each object to implement.


Previous answer details for reference:

You will either have to use Java Generics, potentially with some common interface or base class for the objects in question so that you can then call their methods.

E.g.

public static <T extends Comparable<T>> T maximum(T x, T y, T z) {                      
      T max = x; // assume x is initially the largest       
      if (y.compareTo(max) > 0) {
         max = y; // y is the largest so far
      }

      if (z.compareTo(max) > 0) {
         max = z; // z is the largest now                 
      }

      return max; // returns the largest object   
   }

If, however, you require to call particular methods without knowing the interface for those methods beforehand programmatically, then you're into Reflection territory.

2 Comments

Use a common interface
Yep, common interface or base class is required. The objects cannot be truly "dynamic". You're going to need to know the method signatures of each object to be able to do anything with them. And that is achieved with a common interface or base class. If you don't, then you're in programmatic reflection territory. But it doesn't look like that's what you're trying to do here.

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.