本文通过一个小例子来简单记录下如何使用java反射:
例子作用:获取Android有线网络下的网络信息,适用于Android5.0以上(机顶盒上有有线连接):
先上代码吧:
public void getEthernet(Context context){
try{
//根据反射获取到隐藏类
Class ethernetManager = Class.forName("android.net.EthernetManager");
//获取此类下的getConfiguration方法,无参
Method method = ethernetManager.getMethod("getConfiguration");
//获取EthernetManager类的一个实体对象
Object obj = (context.getSystemService("ethernet"));
//调用上面的method方法,返回的是一个对象ethernetDevInfo
Object ethernetDevInfo = method.invoke(obj);
//获取到ethernetDevInfo对象的class,因为后面还要调用这个类里面的方法
Class devClass = ethernetDevInfo.getClass();
//获取到devClass这个类中的getIpAssignment方法,注:这里获取方法只能通过class,不能通过对象
Method method2 = devClass.getMethod("getIpAssignment");
//调用method2这个方法,其中ethernetDevInfo是上面获取到的类对象,,ipAssignment就是我们要的结果
Enum ipAssignment = (Enum) method2.invoke(ethernetDevInfo);
LogUtils.d(TAG, "ipAssignment:" + ipAssignment);
//获取到devClass这个类中的getStaticIpConfiguration方法
Method getStaticIpConfiguration = devClass.getMethod("getStaticIpConfiguration");
LogUtils.d(TAG, "5555555555:" + 111);
//调用getStaticIpConfiguration这个方法,其中ethernetDevInfo是上面获取到的类对象,方法返回值又是一个对象
Object staticIpConfiguration = getStaticIpConfiguration.invoke(ethernetDevInfo);
//获取到staticIpConfiguration对象的class,因为后面还要调用这个类里面的属性
Class staticIpConfigurationClass = staticIpConfiguration.getClass();
//获取到staticIpConfigurationClass的属性值:ipAddress
Field address = staticIpConfigurationClass.getDeclaredField("ipAddress");
//获取到staticIpConfiguration这个对象中的ipAddress这个属性的值
LinkAddress addressValue = (LinkAddress) address.get(staticIpConfiguration);
}catch(NoSuchMethodError e){
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(NoSuchMethodException e){
e.printStackTrace();
}catch(IllegalAccessException e){
e.printStackTrace();
}catch(InvocationTargetException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace()