简体   繁体   中英

passing different type of objects dynamically on same method

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 .

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
}

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.

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.

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)
}

}

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.

Eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM