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?
Asked
Active
Viewed 161 times
1

Android QS
- 416
- 2
- 8
- 17
-
2Why are you passing the class name instead of the object itself? – Cat Feb 05 '13 at 02: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 Feb 05 '13 at 02:39
-
1Then you're probably looking for this: [Creating an instance using the class name and calling constructor](http://stackoverflow.com/questions/6094575/creating-an-instance-using-the-class-name-and-calling-constructor) – Cat Feb 05 '13 at 02:42
2 Answers
2
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.

user207421
- 305,947
- 44
- 307
- 483
-
-
If it didn't there would be something so seriously wrong with Android that practically nothing would work at all. – user207421 Feb 06 '13 at 02:24
1
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());

iTech
- 18,192
- 4
- 57
- 80