I have an Android app with a Java interface that has a single method, say void doStuff(String className). Others will provide me with .jar files, each containing a class that implements this interface, to be included in my APK. When doStuff() is called, I will receive as a parameter the name of the class that implements the interface. I would like to be able to then obtain an instance of that class and call doStuff() at run-time, without having any specific implementation class types defined in my own code. What is the best way to accomplish this?
-
2Why are you passing the class name instead of the object itself?Cat– Cat2013-02-05 02:27:23 +00:00Commented Feb 5, 2013 at 2:27
-
Sorry, I should have specified that the call to doStuff() comes through to my code from a separate application, so there is no object to pass in. I need to get it to the correct class without having an instantiated object when I receive the call.Android QS– Android QS2013-02-05 02:39:10 +00:00Commented Feb 5, 2013 at 2:39
-
1Then you're probably looking for this: Creating an instance using the class name and calling constructorCat– Cat2013-02-05 02:42:45 +00:00Commented Feb 5, 2013 at 2:42
Add a comment
|
2 Answers
You can do this with a mild amount of reflection:
Class<? Extends MyInterface> myClass = (Class<? Extends MyInterface>)Class.forName(className);
MyInterface myObject = myClass.newInstance();
myObject.doStuff();
This requires that the implementation classes have accessible no-args constructors.
2 Comments
Android QS
Does this work on all versions of Android?
user207421
If it didn't there would be something so seriously wrong with Android that practically nothing would work at all.
You can achieve this with reflection, here is an illustrative example that you can change as you need.
This code asumes that doStuff does not take any arguments and that the class has a default constructor defined.
Class<?> myClass = Class.forName(className);
Method doStuffMethod = myClass.getMethod("doStuff");
doStuffMethod.invoke(myClass.newInstance());