Search code examples
javaandroidreflectionandroid-sourcetelephony

Android - Unable to access some classes under **package android.telephony**


I am trying to access classes stored under android.telephony package using reflection but for some classes I am getting ClassNotFoundException.

Can anyone tell me why some classes can be accessed and some are not even though this classes reside within the same package ?

Ex: public class TelephonyManager can be accessed using reflection as shown below

try {
Class<?> manager1 = Class.forName("android.telephony.TelephonyManager");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}

public class SubscriptionManager cannot be accessed using reflection

try {
Class<?> subscriptionManager = Class.forName("android.telephony.SubscriptionManager");
//Throwing error
} catch (ClassNotFoundException e1) {
e1.printStackTrace(); 
}

both classes belong to the same package android.telephony


Solution

  • Probably because SubscriptionManager was just added in API 22, and the phone or emulator you are using does not have Android 5.1.

    That's how reflection is supposed to work! If a class is not present, the ClassNotFoundException is thrown.