0

I've tried using a variable to invoke a java method, using method.invoke(), as suggested in this example. But it seems there should be an object or something as a parameter in method.invoke(). I've tried using null, but the method didn't get invoked. My code is as follows:

String ACTION = "cart";
Method method = SolverService.class.getDeclaredMethod("Method" + ACTION);
        method.invoke(null);

I've got a method as:

public void Methodcart(){ Toast.makeText(this,"Method called",Toast.LENGTH_LONG).show(); }

PS: I HAVE TO make this method.invoke() work. Otherwise, I need to write a very long list of switch-case statements.I've gone through the documentation but couldn't understand much about the object instance i might need to use here as I'm new to android app developing.

Leo
  • 7,274
  • 5
  • 26
  • 48
Dante
  • 457
  • 1
  • 5
  • 17
  • What is it you're trying to do, in more general terms? Are you attempting to call a method in a service? Both the approaches you've outlined are very unorthodox, and and I am near completely certain there will be a better way. – PPartisan Jul 01 '17 at 07:31
  • You must pass an object instead of null since the method you're trying to call is not static. _"I HAVE TO make this method.invoke() work. Otherwise, I need to write a very long list of switch-case statements"_ seems like you should overthink your design – Felix Jul 01 '17 at 07:33
  • I'm trying to invoke a large number of methods, one at a time, using a single variable. For example, I have methods like methodcart(), methodrail(), methodgrill(), etc., (10s of such methods), and I'm using a variable ACTION so that a method gets invoked as method+ACTION +(); I can decide which method to call by simply changing the value variable ACTION (ACTION=cart / ACTION = rail / and so on). – Dante Jul 01 '17 at 07:38
  • 1
    @Dante What do these methods look like? It sounds as though you should take a more polymorphic/OOP approach. – PPartisan Jul 01 '17 at 07:52
  • @rollback will it work if I make the method a static? How can I catch the retuned Boolean if I use public static boolean Methodcart(){return....} – Dante Jul 01 '17 at 08:27
  • @PPartisan the method is to process simple queries and actions like placing a call or setting an alarm. – Dante Jul 01 '17 at 08:30

2 Answers2

0

You can try something similar to the code shown below (Java Reflection) -

Suppose I have a class ClassWithMethods.java with the methods I want to invoke in some other class as shown below -

public class ClassWithMethods {

    private int counter;

    public void printIt(){
        System.out.println("printIt() no param");
    }

    public void printItString(String temp){
        System.out.println("printIt() with param String : " + temp);
    }
}

Now I also have another class TestApp.java which will invoke methods of the ClassWithMethods class at runtime using Java Reflection -

public class TestApp {

    public static void main(String[] args) {

    //no paramater
    Class noparams[] = {};

    //String parameter
    Class[] paramString = new Class[1];
    paramString[0] = String.class;

    //int parameter
    Class[] paramInt = new Class[1];
    paramInt[0] = Integer.TYPE;

    try{
            //load the ClassWithMethods at runtime
        Class cls = Class.forName("com.myapps.ClassWithMethods");
        Object obj = cls.newInstance();

        //call the printIt method
        Method method = cls.getDeclaredMethod("printIt", noparams);
        method.invoke(obj, null);

        //call the printItString method, pass a String param
        method = cls.getDeclaredMethod("printItString", paramString);
        method.invoke(obj, new String("someString"));



    }catch(Exception ex){
        ex.printStackTrace();
    }
   }
Kunal Chawla
  • 1,236
  • 2
  • 11
  • 24
  • The class array being passed here, 'paramString' has 'String.class' as it's element. May I know why? And what value does 'temp' get from it (I'm using android studio). Is there anyway to return result from the method called? – Dante Jul 01 '17 at 10:52
  • 'temp' is being assigned the value "someString" at runtime. The method has String as its element since everything is basically an object in Java, and to tell the method that the argument is of String type, we've used String.class. – Kunal Chawla Jul 01 '17 at 11:03
  • I've added a more helpful + real world used answer. Please see if it helps. – Kunal Chawla Jul 01 '17 at 11:11
0

I am using Java Reflection in my current project (since you mentioned you are using Android Studio) to get Battery Capacity of device from PowerProfile class which is internal to the Android OS.

public double getBatteryCapacity() {
        Object mPowerProfile = null;
        try {
            mPowerProfile = Class.forName("com.android.internal.os.PowerProfile")
                    .getConstructor(Context.class)
                    .newInstance(getContext());
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
// get access to method named "getAveragePower()" in the class "PowerProfile"
            Method getAveragePower = Class.forName("com.android.internal.os.PowerProfile").getMethod("getAveragePower", String.class);
            //Get total battery capacity in mAh.
            double batteryCapacity = (Double) getAveragePower.invoke(mPowerProfile, "battery.capacity");
            return batteryCapacity;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0.0;
    }

Here is a screenshot of how the actual method structure looks like in the PowerProfile class -

enter image description here

Kunal Chawla
  • 1,236
  • 2
  • 11
  • 24