My project contains this package : com.XYZcontroller
This package includes 3 files
ControllerA.java
public class ControllerA {
public static void insert(Context context, ModelA model) {/*do somethings*/}
}
ControllerB.java
public class ControllerB {
public static void insert(Context context, ModelB model) {/*do somethings*/}
}
MainController.java
I use following code to invoke insert method from Controller A or B it depends on some condition
public static void insert(Context context, Object object) {
Class<?> clazz = Class.forName(mClass); //Controller A or B
Method method = clazz.getMethod("insert", ?);
method.invoke(null, ?);
}
how do i pass arguments ? object may be ModelA or ModelB
I apologize if my wording is not true
You pass the classes as varargs in the method lookup and the instance, which is null for a static invocation and the arguments in the invocation:
boolean useA = true; // use A or B variant:
Method m = clazz.getMethod("insert", Context.class, useA ? ModelA.class : ModelB.class);
m.invoke(null, context, object)
Problem solved:)
ModelA and ModelB implement the same interface, for example Model (not important) , model.getClass()
is an important part of his
public static void insert(Context context, Model model) {
Class<?> clazz = Class.forName(mClass); //Controller A or B
Method method = clazz.getMethod("insert", Context.class, model.getClass());
method.invoke(null, new Object[]{context, model}));
}
Now i can use this :
Controller.insert(this, myModelA);
Controller.insert(this, myModelB);
Thanks all .
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.