I have the following code, and I am getting Instantiation exception when i invoke the newInstnace()
Can you please help
Class cls = Class.forName("com.android.internal.os.BatteryStatsImpl$Uid");
Object obj = cls.newInstance();
Unless the inner class is declared static
, you can't create an instance of the inner class without an instance of the outer class for it to belong to. Once you have one of those, then you need to use reflection to get the inner class's constructor. Note this from the documentation for Class.getConstructor
:
If this
Class
object represents an inner class declared in a non-static context, the formal parameter types include the explicit enclosing instance as the first parameter.
Finally, you need to invoke the constructor's newInstance
method, passing it the instance of the outer class as the first argument.
With an instance of the enclosing class, you don't actually need reflection:
BatteryStatsImpl stats = . . .;
com.android.internal.os.BatteryStatsImpl.Uid obj = stats.new Uid();
EDIT Per request, here's some sample code (with no error checking):
Class<?> statsClass = Class.forName("com.android.internal.os.BatteryStatsImpl");
Object statsObject = statsClass.newInstance();
Class<?> uidClass = Class.forName("com.android.internal.os.BatteryStatsImpl$Uid");
Constructor<?> ctor = uidClass.getConstructor(statsClass);
Object uidObject = ctor.newInstance(statsObject);
Note, of course, that since all this is part of the Android internals (and not part of the published API) it comes with a standard "use at your own risk" warning: The classes you are using are subject to change (or disappearance) without notice in future versions of Android.
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.