简体   繁体   English

在同一方法上动态传递不同类型的对象

[英]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. 在这里, dynamic_objects是不同类型的。 How can I achieve this in Java? 如何用Java实现呢? I do not want to use reflection here . 我不想在这里使用反射

In order to recognize the type of the object you can use the instanceof operator. 为了识别对象的类型,可以使用instanceof运算符。

 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. 这将使您获得更多的面向对象的解决方案,依靠多态而不是反射或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. 使用所有对象的超类-“ Object ”,并使用instanceof运算符检查对象的类型。

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. 每个动态对象仅需要实现CommonInterface接口,即可为要实现的每个对象强制执行method1(),method2(),method3()和property1()签名。


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. 您将不得不使用Java Generics (可能带有某些通用接口)或基类来处理所涉及的对象,以便随后可以调用它们的方法。

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. 但是,如果您需要事先调用某些方法而又不以编程方式知道这些方法的接口,那么您将陷入反射领域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 动态地将不同的对象传递给相同的方法 - Dynamically passing different objects to same method 有没有办法用相同的方法创建不同类型的对象? - Is there a way to create different type objects with same method? 如何对方法名称不同但返回类型相同的不同对象应用相同的过程 - How to apply same process for differents objects with different method name but same returned type 有没有办法在同一方法中传递不同(但特定)类型的对象,并根据 object 的类型有不同的处理方式 - Is there a way to pass different (but specific) types of objects in same method and have different ways to handle based on the type of object 相同方法的不同返回类型 - Different return type for the same method 将不同类的对象作为参数传递给同一方法 - Passing Object of different classes as an argument to same method 将varargs传递给另一种方法作为不同类型 - Passing varargs to another method as different type 将泛型类型动态传递到方法中,以使用该类型构建对象的实例 - Passing the generic type dynamically into the method to build a instance of an object using that type 在同一TCP套接字上接收不同类型的对象 - Recive different type of objects on the same TCP socket Java不同类型的对象作为相同的参数 - Java different type objects as same parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM